在此示例中,当我尝试在componentDidUpdate
生命周期回调期间更新状态时,出现too much recursion
错误。我应该如何更新状态?
import React from 'react';
class NotesContainer extends React.Component {
constructor(props) {
super(props);
this.state = { listOfShoppingItems: [] };
}
componentDidUpdate(nextProps, nextState) {
let newShoppingItems = this.calculateShoppingItems();
this.setState({ listOfShoppingItems: newShoppingItems });
}
calculateShoppingItems() {
let shoppingItemsCart = []
if (this.props.milk < 3) {
let value = "Buy some milk";
shoppingItemsCart.push(value);
}
if (this.props.bread < 2) {
let value = "Buy some bread";
shoppingItemsCart.push(value);
}
if (this.props.fruit < 10) {
let value = "Buy some fruit";
shoppingItemsCart.push(value);
}
if (this.props.juice < 2) {
let value = "Buy some juice";
shoppingItemsCart.push(value);
}
if (this.props.sweets < 5) {
let value = "Buy some sweets";
shoppingItemsCart.push(value);
}
return shoppingItemsCart;
}
render() {
return (
<div>
Etc...
</div>
);
}
}
export default NotesContainer;