【问题标题】:Uncaught TypeError: Cannot read properties of undefined (reading 'reduce')未捕获的 TypeError:无法读取未定义的属性(读取 \'reduce\')
【发布时间】:2023-01-14 05:34:47
【问题描述】:

我正在尝试通过单击添加按钮来更新计数器,因此我通过购物车上下文传递数据并读取它以更新我的计数器,但该应用程序一直给我“减少”的未定义错误

所以这是代码:

const HeaderCartButton = (props) => {
  const cartCtx = useContext(CartContext);

  const numberOfCartItems = cartCtx.items.reduce((curNumber, item) => {
    
    return curNumber + item.amount;
    
  }, 0);

  return (
    <button className={classes.button} onClick={props.onClick}>
      <span className={classes.icon}>
        <CartIcon />
      </span>
      <span>Your Order</span>
      <span className={classes.badge}>{numberOfCartItems}</span>
    </button>
  );
};

所以我相信它无法从“CartContext”中读取变量 这是 CartContext:

const CartContext = React.createContext({
  items: [],
  totalAmount: 0,
  addItem: (item) => {},
  removeItem: (id) => {},
});```



I dont think the problem would be with the React.createContext

【问题讨论】:

  • 我无法使用您提供的代码重现您的问题。 Codesandbox。在“减少”代码块之前尝试 console.log 您的值。此外,有关您的 Context.Provider 的使用方式以及上下文本身如何更新的信息也会有所帮助。

标签: javascript reactjs reduce react-context createcontext


【解决方案1】:
const numberOfCartItems = cartCtx?.items?.reduce((curNumber, item) => {

return curNumber + item.amount; }, 0);

如果将它与 Optional chaining 一起使用,则可以在数据到达后执行操作。我认为这种用法可以解决问题。

【讨论】:

    猜你喜欢
    • 2022-12-21
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2022-12-21
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多