代码之家  ›  专栏  ›  技术社区  ›  ohlr

React setState(空)和force update

  •  0
  • ohlr  · 技术社区  · 6 年前

    所以有反应16 setState(null) 不触发更新

    docs :

    使用空值调用setState不再触发更新这允许 如果要重新呈现,则在更新程序函数中决定。

    但是我需要设定状态 null 并更新组件。我该怎么做? 我试过了以下几项——它们都不管用。

    const [state, setState] = useState(null);
    ....
    ....
    // neither of the following statements update the component
    setState(null) 
    setState(() => {return null});
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Dan    6 年前

    使用钩子时,可以使用一些虚拟状态来强制更新。如果可能的话,一定要考虑一下强制状态更新的必要性。

    function useForceUpdate() {
      const [i, setI] = React.useState(0)
      return React.useCallback(() => setI(i => i + 1), [])
    }
    
    function F() {
      const forceUpdate = useForceUpdate()
      ....
      forceUpdate()
    }