React:如何在事件处理程序中调用 React 钩子?

541*_*060 4 javascript reactjs react-hooks

我在反应功能组件中有以下代码。当我单击按钮并运行处理程序时,发生错误: Invalid hook call. Hooks can only be called inside of the body of a function component.

const handleClick = () => {
  const [count, setCount] = useState(x); // this is wrong
};
Run Code Online (Sandbox Code Playgroud)

我试图寻找修复,有人建议:

const [count, setCount] = useState(0);

const handleClick = () => {
  setCount(x); // setCount is ok, but I cannot set other dynamic states
};
Run Code Online (Sandbox Code Playgroud)

但是,我的count状态是动态的,我无法从一开始就全部初始化。当我使用类组件时,这很容易。

// old syntax from class components
state = {
  count: 0
};

const handleClick = () => {
  this.setState({
    other_count: x
  })
};
Run Code Online (Sandbox Code Playgroud)

功能组件如何实现同样的效果?

zyn*_*nkn 5

如果要state动态使用,请使用objectas state

请记住不变性

const [state, setState] = useState({ count: 0 });

const handleClick = () => {
  setState({...state, other_count: x });
}
Run Code Online (Sandbox Code Playgroud)