Reactjs 使用对useState钩子的回调来更新setState
我正在将使用的Reactjs 使用对useState钩子的回调来更新setState,reactjs,Reactjs,我正在将使用的setStates从基于类的组件更新为功能组件。我有一些用例需要关闭。代码是 this.setState( ({ notifications }) => ({ notifications: [...notifications, notification], }), () => timeout !== undefined && window.setTimeout(closeNotification, timeout)
setStates
从基于类的组件更新为功能组件。我有一些用例需要关闭。代码是
this.setState(
({ notifications }) => ({
notifications: [...notifications, notification],
}),
() =>
timeout !== undefined && window.setTimeout(closeNotification, timeout)
);
如何使用
useState
钩子更新此文件。我假设useState没有返回承诺,所以我不能使用。然后。如果是这样的话,更新此函数的最佳方法是什么?可能是这样的
const [notifications, setNotifications] = useState([]);
const doSomething = () => {
setNotifications([ /* ... */ ]);
}
useEffect(() => {
let timer;
if(timeout !== undefined) {
timer = setTimeout(closeNotification, timeout);
}
return () => clearTimeout(timer)
}, [notifications]);
也许是这样
const [notifications, setNotifications] = useState([]);
const doSomething = () => {
setNotifications([ /* ... */ ]);
}
useEffect(() => {
let timer;
if(timeout !== undefined) {
timer = setTimeout(closeNotification, timeout);
}
return () => clearTimeout(timer)
}, [notifications]);
您可以使用useState
和useffect
钩子来实现相同的结果,如下所示:
const [notifications, setNotifications] = useState([]);
useEffect(() => {
// Close Notifications Here
}, [notifications]);
// To update the state use the setNotifications function like so
setNotifications(prevState => [...prevState, newNotification]);
更新通知时,useffect
钩子将运行。您可以使用useState
和useffect
钩子实现相同的结果,如下所示:
const [notifications, setNotifications] = useState([]);
useEffect(() => {
// Close Notifications Here
}, [notifications]);
// To update the state use the setNotifications function like so
setNotifications(prevState => [...prevState, newNotification]);
更新通知时,useffect
钩子将运行。在状态更新后,可以使用useffect
钩子运行一些代码。要使其正常工作,您需要在useffect
hook的依赖项数组中添加状态。我想我必须这样做。我只是希望有一个更线性的方法来解决这个问题。你可以使用useffect
hook在状态更新后运行一些代码。要使其正常工作,您需要在useffect
hook的依赖项数组中添加状态。我想我必须这样做。我只是希望有一个更线性的方法来解决这个问题。useffect
应该返回一个卸载清理函数,可以清除超时以避免泄漏。useffect
应该返回一个卸载清理函数,可以清除超时以避免泄漏。