因此,使用 React 16 setState(null)
不会触发更新
docs :
Calling setState with null no longer triggers an update. This allows you to decide in an updater function if you want to re-render.
但是我需要设置状态null
并更新组件。我怎样才能做到这一点?
我尝试了以下方法 - 它们都不起作用。
const [state, setState] = useState(null);
....
....
// neither of the following statements update the component
setState(null)
setState(() => {return null});
最佳答案
在使用钩子(Hook)时,您可以使用一些虚拟状态来强制更新。请考虑在可能的情况下解决强制执行状态更新的需要。
function useForceUpdate() {
const [i, setI] = React.useState(0)
return React.useCallback(() => setI(i => i + 1), [])
}
function F() {
const forceUpdate = useForceUpdate()
....
forceUpdate()
}
关于javascript - React setState(null) 并强制更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58676257/