反应中 useCallback() 钩子上缺少依赖项(道具)错误

时间:2021-07-30 13:20:08

标签: reactjs react-hooks

我是 React 的初学者,并且缺少对 useCallback() 钩子的依赖。

我试过了:

const { updatedCartForCheckout } = props;

和使用

updatedCartForCheckout(response.data.data);

useCallback() 中并将 updatedCartForCheckout 设置为依赖项,但我遇到了循环。

这里是错误信息:webpackHotDevClient.js:138 src\components\UI\Navbar.js 第 55:6 行:React Hook useCallback 缺少依赖项:'updatedCartForCheckout'。包括它或删除依赖数组 react-hooks/exhaustive-deps

Navbar.js

const getCartInfo = useCallback(() => {
const cartData = JSON.parse(localStorage.getItem("cartDetails"));

if (cartDataFromStoreFront || cartData) {
  getCart(
    cartDataFromStoreFront
      ? cartDataFromStoreFront.cartId
      : false || cartData.cartId
  )
    .then((response) => {
      if (response.data.status === "success") {
        setCartDetails(response.data.data);
        props.updatedCartForCheckout(response.data.data);
        if (response.data.data.items.length < 1) {
          localStorage.removeItem("cartDetails");
        }
      }
    })
    .catch((error) => {
      if (error) {
        if (error.response) {
          if (error.response.data) {
            console.log(error.response.data.message);
          }
        }
      }
    });
} }, [cartDataFromStoreFront]);

 useEffect(() => {
window.$("#slide-cart").hide();
setIsAuthenticated(!!tokenFromLocalStorage || !!token);
getCartInfo();
}, [tokenFromLocalStorage, token, getCartInfo]);

app.js

  const [updatedCartForCheckout, setUpdatedCartForCheckout] = useState(null);
    const updatedCartForCheckoutHandler = (updatedCartForCheckout) => {
  setUpdatedCartForCheckout(updatedCartForCheckout);
};
  return (
<>
  <Navbar
    cartDataFromStoreFront={cartData}
    updatedCartForCheckout={updatedCartForCheckoutHandler}
  />
<Route path="/checkout">
          <Checkout updatedCartForCheckout={updatedCartForCheckout} />
        </Route>

checkout.js

const Checkout = (props) => {
  if (props.updatedCartForCheckout) {
cartDetails = props.updatedCartForCheckout.items;
subTotal = props.updatedCartForCheckout.subtotal;
deliveryCharge = props.updatedCartForCheckout.delivery_charge;
tax = props.updatedCartForCheckout.tax;
total = props.updatedCartForCheckout.total;


}

0 个答案:

没有答案