在VSC上编译时,没有出现此错误,但是当我在浏览器中加载页面时,这就是我看到的:
TypeError:无法读取未定义的属性“ filter”
和:
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>
);
}
答案 0 :(得分: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>
)
}
}