[英]useEffect missing dependency when using redux useDispatch
I wanna fetch my categories whenever my component is mounted using react hooks useEffect
and not on every re-render.每当我的组件使用 react hooks
useEffect
而不是每次重新渲染时,我都想获取我的类别。 But i keep on getting this warning React Hook useEffect has a missing dependency:'dispatch'
.但是我一直收到这个警告
React Hook useEffect has a missing dependency:'dispatch'
。
Here's my code:这是我的代码:
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();
}, []);
You can safely add the dispatch function to the useEffect dependency array.您可以安全地将 dispatch 函数添加到 useEffect 依赖项数组中。 If you look the react-redux documentation, specially the hooks section, they mention this "issue".
如果您查看 react-redux 文档,特别是钩子部分,他们会提到这个“问题”。
The dispatch function reference will be stable as long as the same store instance is being passed to the .
只要将相同的 store 实例传递给 . Normally, that store instance never changes in an application.
通常,该存储实例永远不会在应用程序中更改。
However, the React hooks lint rules do not know that dispatch should be stable, and will warn that the dispatch variable should be added to dependency arrays for useEffect and useCallback.
但是,React hooks lint 规则不知道 dispatch 应该是稳定的,并且会警告应该将 dispatch 变量添加到 useEffect 和 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])
} }
Add dispatch
to your dependency array (which is currently empty).将
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]);
It might be a problem with ignored promise.忽略承诺可能是一个问题。
fetchCategories() returns a promise.
You can try你可以试试
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());
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.