【发布时间】:2020-05-30 21:57:52
【问题描述】:
我们已经迁移到“React 功能组件”而不是“基于类的组件”。我找不到 setState callback function 的替代逻辑。即,我有一个带状态的功能组件,我想创建一个事件处理函数,它可以按顺序多次改变状态,需要注意的是我不知道状态的当前值(可能是true/@987654324 @)。下面的例子可能更有意义。
const Example = () => {
const [ openDoor, setOpenDoor ] = useState(false);
// the following handler should swich 'openDoor' state to inverse of
// current state value. Then after setTimeout duration, inverse it again
const toggleOpenDoor = () => {
setOpenDoor(!openDoor);
// within setTimeout below, '!openDoor' does not work because it still
// receives the same value as above because of async nature of
// state updates
setTimeout(() => setOpenDoor(!openDoor), 500)
}
return(...);
}
在基于class 的组件中,我们有回调参数,它将在上次更新后更新状态。如何使用状态挂钩在上述功能组件中实现相同的功能?
【问题讨论】:
-
我认为你可以做类似
setOpenDoor(prevOpenDoor => !prevOpenDoor)
标签: javascript reactjs react-hooks