【问题标题】:React Hook useEffect has missing dependencies: 'dispatch' and 'init' - when using useDispach in useEffectReact Hook useEffect 缺少依赖项:'dispatch' 和 'init' - 在 useEffect 中使用 useDispach 时
【发布时间】:2020-06-07 05:08:17
【问题描述】:

我正在尝试在 redux 中创建某种初始化状态,因此当应用加载时,应用会从 redux(带有 thunk)获取一些数据并获取数据。

所以我只需要它一次,为此我将 [] 放在 useFffect 参数中, 但我收到以下错误:

  Line 32:6:  React Hook useEffect has missing dependencies: 'dispatch' and 'init'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

我无法将 useDispatch 插入到 useEffect 中

  const { isReady } = useSelector<AppState, AppProps>((state: AppState) => {
    return {
      isReady: state.appStatus.isReady
    };
  });

  const dispatch = useDispatch();
  const init = initilizeAction();

  useEffect(() => {
    dispatch(init);
  }, []);

【问题讨论】:

  • 作为一种解决方法,您可以通过添加 // eslint-disable-next-line no-use-before-define 来禁用它。

标签: reactjs redux use-effect


【解决方案1】:

您可以将initilizeAction() 移动到useEffect,并将调度添加为依赖项(它不应更改,因此只会触发一次)。

  const dispatch = useDispatch();

  useEffect(() => {
    const init = initilizeAction();
    dispatch(init);
  }, [dispatch]);

【讨论】:

    猜你喜欢
    • 2020-02-25
    • 2020-06-11
    • 2021-02-23
    • 2020-10-26
    • 2020-07-24
    • 2019-10-24
    • 2020-05-27
    • 2020-03-07
    • 2020-03-30
    相关资源
    最近更新 更多