[useEffect在使用redux useDispatch时缺少依赖项

问题描述 投票:0回答:1

每当我使用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();
}, []);
reactjs redux react-redux react-hooks
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]);
© www.soinside.com 2019 - 2024. All rights reserved.