【问题标题】:ERROR: React Hook useEffect has a missing dependency: 'dispatch'. Either include it or remove the dependency array错误:React Hook useEffect 缺少依赖项:'dispatch'。包括它或删除依赖数组
【发布时间】:2023-04-09 02:20:01
【问题描述】:

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

错误:React Hook useEffect 缺少依赖项:'dispatch'。要么包含它,要么移除依赖数组

但我的代码不会在屏幕上呈现。

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

【问题讨论】:

  • 嗨@braspy。你问的问题很好。当您对答案感到满意时,请务必选择“正确答案”来结束问题(并奖励给出最佳答案的人)。当您达到 15 个代表点时,您还可以为答案投票 - 这是向提供有用答案的人表示感谢的另一种方式。 (无论是支持还是选择正确的答案都不会花费任何东西 - 但两种行为都会给给出答案的人奖励积分。)

标签: reactjs dependencies dispatch


【解决方案1】:

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

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

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

这样做的缺点是,只要您的 userDatadispatch 更改,您的效果就会运行。您可以使用// eslint-disable-next-line react-hooks/exhaustive-deps 忽略此规则。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-29
    • 2020-07-19
    • 2020-05-31
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    • 2021-09-10
    • 2020-09-26
    相关资源
    最近更新 更多