带有空依赖项的useEffect中无法调用自定义反应钩子

时间:2019-12-09 09:36:45

标签: reactjs react-hooks

我是React的新手,我正在做一个带有react新功能“ Hooks”的项目。

我遇到了一个问题,需要对此进行解释。

作为文档,要实现“ componentDidMount”,只需在依赖项参数中传递空数组即可。

  useEffect(() => {
    // some code here
  }, []);

然后我可以在useEffect中调用调度函数来更新状态。

const [flag, setFlag] = useState(false);

useEffect(() => {
  setFlag(true);
}, []);

以上代码可完美运行,而不会发出警告或任何错误。

现在我有了我的自定义钩子,但是我无法在效果内调用我的调度。

const [customFlag, setCustomFlag] = useCustomHook();

useEffect(() => {
  setCustomFlag(true);
}, []);

这是我的自定义钩子。

function useCustomHook() {
  const [success, setSuccess] = useState(false):

  const component = <div>{ success ? "Success" : "Fail" }</div>;
  const dispatch = useCallback(success => {
    setSuccess(success);
  }, []);

  return [component, dispatch]; 
}

使用上面的代码,它要求我将setCustomFlag放入依赖项数组中。

我不明白为什么。他们之间有什么不同?

感谢分享。

2 个答案:

答案 0 :(得分:0)

可能是,您的自定义钩子在每次调用时都返回setCustomFlag的不同实例。这意味着useEffect()将始终使用第一个值(在第一个渲染中返回)。尝试通过调用useCallback() / useMemo()钩子来记住它:

function useCustomHook() {
  ...

  const setCustomFlag = useCallback(/* setCustomFlag body here */, []);
}

让您的自定义钩子来源多说会很好。

答案 1 :(得分:0)

原因是useState中的setFlag是一个已知的依赖项,它的值在渲染之间不会改变,因此您不必将其声明为依赖项

React eslint-plugin-react-hooks无法确定您的自定义钩子,这就是为什么您需要将其放入依赖项列表中的原因

这取自eslint-plugin-react-hooks

      // Next we'll define a few helpers that helps us
      // tell if some values don't have to be declared as deps.

      // Some are known to be static based on Hook calls.
      // const [state, setState] = useState() / React.useState()
      //               ^^^ true for this reference
      // const [state, dispatch] = useReducer() / React.useReducer()
      //               ^^^ true for this reference
      // const ref = useRef()
      //       ^^^ true for this reference
      // False for everything else.
      function isStaticKnownHookValue(resolved) {
      }
相关问题