在反应中添加一个计数器

Add a counter in react

我正在尝试制作购物车,我想在 header 中添加一个计数器,但我收到一条错误消息“无法读取未定义的 属性 'length'” .

这是 header 的代码:

import React,{useState} from 'react';
function Toolbar(props){
    const {cart} = props;
    return(
<header>
    <button>
    <span>
        Go To Cart: 
      {cart.length}</span>
        </button>
    </header>
    )

}
export default Toolbar;

这是产品页面的代码。它在控制台日志中计数,但在屏幕上不计数。

 import React, {useState} from 'react'
function Products(props) {
    const [cart, setCart]=useState([]);
    const addtoCart=(props)=>{
        console.log('we are in addToCart');
        setCart([...cart,props]);
    };
    return(
        <div >
        <h1>Products</h1>
        <div className="product" key={props.id}>
      <h3>{props.name}</h3>
      <h4>{props.cost}</h4>
      <img src ={props.image} alt="/"/>
      
      <button onClick={()=>addtoCart(props)}>Add to Cart</button>
      </div>
      </div>
    );
   
  }
  
  export default Products;

您似乎没有将任何道具传递给 ToolBar 组件。

更新: 根据您分享的评论和代码框 link,这确实是您的问题。没有传递给 ToolBar 组件的道具。

我在CodeSandBox上修改了这里的代码:

https://codesandbox.io/s/serve-humanity-8hm17

我想指出一个事实,如果您将 props 传递给 ToolBar 组件,但组件在数据可用之前呈现,在这种情况下,您也会收到此错误。

在这种情况下,您可以添加一个检查:

 <span>
        Go To Cart: 
     {cart.length && cart.length}
 </span>

注意:交叉验证你是否真的收到了任何道具。在你的 Toolbar 组件声明它之后做一个 console.log(props.cart)

function Toolbar(props){
    console.log(props);
    const {cart} = props;
    return(...)
}

这样您就可以更好地了解数据的情况,并且可以更好地调试您的应用:)