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



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

功能部件如何达到同样的效果?

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

请记住不变性

const [state, setState] = useState({ count: 0 });
const handleClick = () => {
setState({...state, other_count: x });
}

您可以使用多个状态或单个状态中的对象。

第一种方式:

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

演示第二种方式。

相关内容

  • 没有找到相关文章

最新更新