【发布时间】:2019-02-02 02:06:01
【问题描述】:
我试图让这个函数在子组件中的点击调用中触发。
getTotalOfItems = () => {
console.log('anything at all?')
if (this.props.cart === undefined || this.props.cart.length == 0) {
return 0
} else {
const items = this.props.cart
var totalPrice = items.reduce(function (accumulator, item) {
return accumulator + item.price;
}, 0);
this.setState({
estimatedTotal: totalPrice
});
};
}
这是从购物车组件中触发的点击
<button onClick={() => {props.addToCart(item); props.getPrice.bind(this)} }>+</button>
购物车组件正在此处添加到 ItemDetails 组件中
export default class ItemDetails extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
render() {
return(
<div>
<Button
className="item-details-button"
bsStyle="link"
onClick={() => this.setState({open: !this.state.open})}
>
{this.state.open === false ? `See` : `Hide`} item details
{this.state.open === false ? ` +` : ` -`}
</Button>
<Collapse in={this.state.open}>
<Cart
getPrice={this.props.getPrice}
/>
</Collapse>
</div>
)
}
}
最后像这样将ItemDetails组件添加到app.js中
render() {
return (
<div className="container">
<Col md={9} className="items">
<ProductListing products={this.props.initialitems} />
</Col>
<Col md={3} className="purchase-card">
<SubTotal price={this.state.total.toFixed(2)} />
<hr />
<EstimatedTotal
price={this.state.estimatedTotal.toFixed(2)} />
<ItemDetails
price={this.state.estimatedTotal.toFixed(2)}
getPrice={ () => this.getTotalOfItems() }
/>
<hr />
<PromoCodeDiscount
giveDiscount={ () => this.giveDiscountHandler() }
isDisabled={this.state.disablePromoButton}
/>
</Col>
</div>
);
};
如果我在 this.getTotalOfItems() 之前删除 () = >,它会触发 onClick 上的函数,但是它会导致重新渲染应用程序的无限循环,从而导致错误。
有没有办法解决这个问题?我是 React 的新手,这是我第一个使用它的项目之一。任何建议将不胜感激。
很抱歉,如果没有很好地解释这一点,如果需要,我很乐意提供任何其他信息。
谢谢!
【问题讨论】:
标签: javascript reactjs function components