ERROR: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array

ERROR: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array

正在尝试发送一个动作,但我的终端出现了这个错误。

ERROR: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array

但我的代码无法在屏幕上呈现。

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]);
}

这是一个 linting 规则 exhaustive-deps。目的是让您仅使用第二个参数中使用的道具或状态变量。

因为您的第二个参数不包含 dispatch,所以您收到了一个错误。如果您将 dispatch 添加到应该消失的第二个参数。

useEffect(() => {
  // your logic here 
}, [props.user.userData, dispatch])

这样做的缺点是,只要 userDatadispatch 发生变化,您的效果就会 运行。您可以使用 // eslint-disable-next-line react-hooks/exhaustive-deps.

忽略此规则