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

时间:2019-10-21 05:29:09

标签: javascript reactjs react-hooks

我在react功能组件中有以下代码。当我单击按钮并运行处理程序时,发生错误: 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
};

我尝试搜索此修复程序,有人建议:

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

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

但是,我的count状态是动态的,我无法从头开始初始化所有内容。当我使用类组件时,这很容易。

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

const handleClick = () => {
  this.setState({
    other_count: x
  })
};

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

2 个答案:

答案 0 :(得分:3)

如果要动态使用state,请将object用作state

请牢记不变性

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

const handleClick = () => {
  setState({...state, other_count: x });
}

答案 1 :(得分:3)

您可以使用多个状态,也可以在一个状态中使用一个对象。

第一种方式:

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

const handleClick = () => {
  // count is already available to you.. so update the other state
  setOtherCount(x);
};

第二种方式:

const [compState, setCompState] = useState({ count: 0, other_count: 0 });

const handleClick = () => {
  setCompState(prevState => { ...prevState, other_count: x });
};

DEMO用于第二种方式。