【问题标题】:How to fix React Redux and React Hook useEffect has a missing dependency: 'dispatch'如何修复 React Redux 和 React Hook useEffect 缺少依赖项:'dispatch'
【发布时间】:2020-05-27 04:54:31
【问题描述】:

React Hook useEffect 缺少一个依赖项:'dispatch'。要么包含它,要么移除依赖数组 react-hooks/exhaustive-deps

我在这样的功能组件上使用来自 React Redux 的 useDispatch() Hook:

const Component = () => {
  const dispatch = useDispatch();
  const userName = useSelect(state => state.user.name);

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

  return (
    <div>Hello {userName}</div>
  );
};

export default Component;

如何在不删除依赖数组 react-hooks/exhaustive-deps 的情况下删除此警告,这对于避免其他错误很有用。

【问题讨论】:

    标签: javascript reactjs react-redux react-hooks use-effect


    【解决方案1】:

    为避免该警告,只需将dispatch 添加到依赖数组即可。这不会调用重新渲染,因为调度值不会改变。

    const Component = () => {
      const dispatch = useDispatch();
      const userName = useSelect(state => state.user.name);
    
      useEffect(() => {
        dispatch(getUserInformation());
      }, [userId, dispatch]);
    
      return (
        <div>Hello {userName}</div>
      );
    };
    
    export default Component;
    

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 2020-07-12
      • 1970-01-01
      • 2021-02-23
      • 2019-10-24
      • 2021-10-16
      • 2020-10-26
      • 2020-06-07
      • 2020-03-07
      相关资源
      最近更新 更多