我写了一个代码来计算购物车的总数量和总价格。但是,向子组件发送引用存在一个问题。 (App.js-> Navigation.js-> CartProcess.js-> CartList.js,App.js-> CartList.js(用于路由))CartProcess的链接如下所示。这是下面显示的问题。
React无法识别DOM元素上的totalQuantity
属性。如果您有意让它作为自定义属性出现在DOM中,请将其拼写为小写totalquantity
。如果不小心从父组件传递了它,请将其从DOM元素中删除。
React无法识别DOM元素上的totalPrice
属性。如果您有意让它作为自定义属性出现在DOM中,请将其拼写为小写totalprice
。如果不小心从父组件传递了它,请将其从DOM元素中删除。
<DropdownItem>
<Link to="/cart"
totalQuantity={ this.props.totalQuantity}
totalPrice={ this.props.totalPrice }
>Cart Detail</Link>
</DropdownItem>
App.js还包括CartList组件以显示购物车详细信息。
渲染部分
<Route exact path="/cart" render={
routeProps => (
<CartList
{...routeProps}
cart={this.state.cart}
removeFromCart={this.removeFromCart}
totalQuantity={this.totalQuantity}
totalPrice={this.totalPrice}
/>
)
} />
}
当我像这样的顺序从父组件调用totalQuantity和totalPrice函数时。
App.js <- Navigation.js <- CartProcess.js
我显示以下错误。
错误:已超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。
CartList.js
renderTotalPriceAndTotalQuantity(){
return (
<div>
<Alert color="primary">
Total Price : { this.props.totalPrice() }
</Alert>
<Alert color="secondary">
Total Quantity : { this.props.totalQuantity() }
</Alert>
</div>
)
}
App.js
totalQuantity = () => {
console.log("totalQuantity");
this.setState({
totalQuantity: this.state.cart.reduce(
(sum = 0, cartItem) => sum + cartItem.quantity,
0
)
});
console.log(this.state.totalQuantity);
}
totalPrice = () => {
console.log("totalPrice");
this.setState({
totalPrice: this.state.cart.reduce(
(sum = 0, cartItem) => sum + cartItem.quantity * cartItem.product.unitPrice,
0
)
});
console.log(this.state.totalPrice);
}
我该如何解决问题?
谢谢。
在CartList.js
中,您实际上是在html中调用导致此问题的函数。尝试这样做:
renderTotalPriceAndTotalQuantity(){
return (
<div>
<Alert color="primary">
Total Price : { this.props.totalPrice }
</Alert>
<Alert color="secondary">
Total Quantity : { this.props.totalQuantity }
</Alert>
</div>
)
}