【发布时间】:2020-02-17 04:28:03
【问题描述】:
我在反应功能组件中有以下代码。当我单击按钮并运行处理程序时,会发生错误:
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
})
};
功能组件如何达到同样的效果?
【问题讨论】:
-
你能发布你的 package.json 吗?
-
你能发布你的整个组件吗
-
“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"
-
other_count是计算密钥吗?
标签: javascript reactjs react-hooks