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

5

我在一个React函数组件中有以下代码。当我点击按钮并运行处理程序时,会出现错误: 无效的钩子调用。hook只能在函数组件的主体内调用。

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
  })
};

如何为函数式组件实现相同的效果?

你能发布你的 package.json 文件吗? - Oleg
你能否发布你的整个组件? - C. J. Tantay
"react": "^16.9.0", "react-dom": "^16.9.0", "react-redux": "^7.1.1", "react-router-dom": "^5.0.1", "react-scripts": "2.1.8" - 5413668060
other_count 是一个计算键吗? - Joseph D.
2个回答

5

如果您想动态使用 state,请将 object 作为 state

请记住保持不可变性

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

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

4
您可以在单个状态中使用多个状态或对象。
第一种方式:
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 });
};

点此查看第二种方法的演示效果


如果我从不同的函数更新多个状态,会出现问题吗?例如 state = { a: 1, b: 2 } 并且从不同的异步函数中调用 setState({ ...state, a: 10 })setState({ ...state, b: 20 }),会有任何竞争条件吗? - 5413668060
1
如果您正在异步函数中进行更新,则可以使用另一种方式来更新状态。setState(prevState => { ...prevState, a:10 }) - Kishor
@5413668060 你也可以查看这个链接。我使用了setTimeout来测试异步行为。https://codesandbox.io/s/upbeat-bird-l97e4?fontsize=14 - Kishor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接