[英]ERROR: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array
Trying to dispatch an action but i got this error in my terminal.试图调度一个动作,但我的终端出现了这个错误。
ERROR: React Hook useEffect has a missing dependency: 'dispatch'.
错误:React Hook useEffect 缺少依赖项:'dispatch'。 Either include it or remove the dependency array
包括它或删除依赖数组
yet my code wont render on the screen.但是我的代码不会在屏幕上呈现。
function CartPage(props) {
const dispatch = useDispatch();
const [Total, setTotal] = useState(0);
const [ShowTotal, setShowTotal] = useState(false);
const [ShowSuccess, setShowSuccess] = useState(false);
useEffect(() => {
let cartItems = [];
if (props.user.userData && props.user.userData.cart) {
if (props.user.userData.cart.length > 0) {
props.user.userData.cart.forEach((item) => {
cartItems.push(item.id);
});
dispatch(getCartItems(cartItems, props.user.userData.cart)).then(
(response) => {
if (response.payload.length > 0) {
calculateTotal(response.payload);
}
},
);
}
}
}, [props.user.userData]);
}
This is a linting rule exhaustive-deps
.这是一个 linting 规则
exhaustive-deps
。 The purpose is to get you to only use props or state variables used in your second argument.目的是让您仅使用第二个参数中使用的道具或 state 变量。
Because your second argument does not include dispatch
you are getting an error.因为你的第二个参数不包括
dispatch
你得到一个错误。 If you add dispatch to your second argument that should go away.如果您将调度添加到您的第二个参数,则应该 go 离开。
useEffect(() => {
// your logic here
}, [props.user.userData, dispatch])
The downside to this is that, your effect will run whenever your userData
or dispatch
changes.这样做的缺点是,只要您的
userData
或dispatch
更改,您的效果就会运行。 You can ignore this rule with // eslint-disable-next-line react-hooks/exhaustive-deps
.您可以使用
// eslint-disable-next-line react-hooks/exhaustive-deps
忽略此规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.