gpt4 book ai didi

reactjs - 使用 redux useDispatch 时 useEffect 缺少依赖项

转载 作者:行者123 更新时间:2023-12-03 14:23:49 26 4
gpt4 key购买 nike

每当我使用 react 钩子(Hook)安装组件时,我都想获取我的类别 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();
}, []);

最佳答案

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

The dispatch function reference will be stable as long as the samestore instance is being passed to the . Normally, that storeinstance never changes in an application.

However, the React hooks lint rules do not know that dispatch shouldbe stable, and will warn that the dispatch variable should be added todependency arrays for useEffect and useCallback. The simplest solution is to do just that:

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

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

关于reactjs - 使用 redux useDispatch 时 useEffect 缺少依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59350881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com