【问题标题】:How to solve TypeError: Cannot read property 'filter' of undefined如何解决 TypeError:无法读取未定义的属性“过滤器”
【发布时间】:2019-05-21 04:27:37
【问题描述】:

我在 VSC 上编译时没有收到此错误,但是当我在浏览器中加载页面时,我看到的是:

TypeError: 无法读取未定义的属性“过滤器”

和:

  10 |   product={product}
  11 |   addToCart={props.addToCart}
  12 |   removeFromCart={props.removeFromCart}
> 13 |   cartItem={
     | ^  
  14 |     props.cart.filter(cartItem => cartItem.id === product.id)[0]
  15 |   }
  16 | />

这是完整的功能:

function ProductListing(props) {
  return (
    <div className="product-listing">
      {props.products.map(product => (
        <ProductListItem
          product={product}
          addToCart={props.addToCart}
          removeFromCart={props.removeFromCart}
          cartItem={
            props.cart.filter(cartItem => cartItem.id === product.id)[0]
          }
        />
      ))}
    </div>
  );
}

【问题讨论】:

  • 错误表示props.cartundefined
  • 换句话说,要么你没有将cart 作为道具传递给元素,要么你传递的东西是undefined
  • 可能购物车没有作为道具传递给 ProductListing 组件,或者它在初始渲染中不可用。
  • 这是一个非常小的示例,可以帮助您了解问题的根源。我看到你在标签上使用了 redux。您在某处使用 mapStateToProps 吗?就像他们说的那样,购物车是未定义的。您需要追踪您将购物车作为道具传递的地方。
  • 在尝试过滤它之前确保该道具存在:props.cart &amp;&amp; props.cart.filter(cartItem =&gt; cartItem.id === product.id)[0] 但这可能只是将问题转移到您的ProductListItem 我们需要有关该道具来自何处的更多详细信息

标签: javascript html reactjs redux


【解决方案1】:

确保在父级中有条件地渲染子级,以便仅在 props.cart 准备好时才渲染它。

export class ParentContainer extends Component {

    constructor(){
      super()
      this.state  = {
        cart: []
        isLoading: true
      }
    }

    componentWillMount(){
      // fetch('/some/endpoint')
      // massage your data and then push it to state
      .then(card => {
        this.setState({cart, isLoading: false})
      })
    }

    render() {
      return (
        <Fragment>
          {this.state.isLoading ? ( // evalutate if Data is ready to be passed
            <Fragment />
            ) : (
              <CartInformation cart={this.state.cart} />
            )
          }
        </Fragment>
      )
    }
  }

【讨论】:

    猜你喜欢
    • 2021-12-26
    • 2019-03-26
    • 2018-12-21
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2020-10-22
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多