我在一个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
})
};
如何为函数式组件实现相同的效果?
other_count
是一个计算键吗? - Joseph D.