使用redux useDispatch时useEffect缺少依赖项

时间:2019-12-16 05:17:28

标签: reactjs redux react-redux react-hooks

每当我使用react钩子useEffect挂载组件时,而不是在每次重新渲染时,我都想获取类别。但是我继续收到此警告React Hook useEffect has a missing dependency:'dispatch'

这是我的代码:

const categories = useSelector(state => state.category.categories);
const dispatch = useDispatch();

useEffect(() => {
    console.log('effecting');
    const fetchCategories = async () => {
       console.log('fetching');
       try {
            const response = await axios.get('/api/v1/categories');
            dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories();
}, []);

3 个答案:

答案 0 :(得分:3)

您可以安全地将 dispatch 函数添加到 useEffect 依赖项数组中。如果您查看 react-redux 文档,特别是 hooks 部分,他们会提到这个“问题”。

<块引用>

dispatch 函数引用会稳定,只要相同 store 实例正在传递给 .平时那家店 实例永远不会在应用程序中发生变化。

然而,React hooks lint 规则不知道 dispatch 应该 是稳定的,并会警告应该将调度变量添加到 useEffect 和 useCallback 的依赖数组。最简单的解决方案就是这样做:

export const Todos() = () => {
const dispatch = useDispatch();

useEffect(() => {
    dispatch(fetchTodos())
  // Safe to add dispatch to the dependencies array
  }, [dispatch])

}

答案 1 :(得分:0)

dispatch添加到您的依赖项数组(当前为空)。

useEffect(() => {
    console.log('effecting');
    const fetchCategories = async () => {
       console.log('fetching');
       try {
            const response = await axios.get('/api/v1/categories');
            dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories();
}, [dispatch]);

答案 2 :(得分:0)

可能是忽略诺言的问题。

fetchCategories() returns a promise.

您可以尝试

useEffect(() => {
    const fetchCategories = async () => {
       try {
            const response = await axios.get('/api/v1/categories');
            await dispatch(initCategory(response.data.data.categories));
       } catch (e) {
           console.log(e);
       }
    }

    fetchCategories().then(res => (console.log(res());
}, []);
相关问题