反应挂钩useEffect缺少依赖项:'dispatch'。要么包含它,要么删除依赖项数组react-hooks / exhaustive-deps
我在这样的功能组件上使用来自React Redux的useDispatch()
钩子:
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,这对于避免其他错误很有用。
答案 0 :(得分:5)
要避免该警告,只需将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;
答案 1 :(得分:0)
您可以将dispatch
添加到useEffect内的方括号中。
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;
答案 2 :(得分:0)
最新答案,但所有投票均投给第一个答案
const dispatch = useDispatch();
const userName = useSelect(state => state.user.name);
useEffect(() => {
dispatch(getUserInformation());
}, [userId, dispatch]);