Javascript 在react中更新状态时递归过多
在本例中,当我尝试在Javascript 在react中更新状态时递归过多,javascript,reactjs,Javascript,Reactjs,在本例中,当我尝试在componentdiddupdate生命周期回调期间更新状态时,我得到了一个太多递归错误。我应该如何更新状态 import React from 'react'; class NotesContainer extends React.Component { constructor(props) { super(props); this.state = { listOfShoppingItems: [] }; } componentDidUpd
componentdiddupdate
生命周期回调期间更新状态时,我得到了一个太多递归
错误。我应该如何更新状态
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;
从“React”导入React;
类NotesContainer扩展React.Component{
建造师(道具){
超级(道具);
this.state={listOfShoppingItems:[]};
}
componentDidUpdate(下一步,下一步状态){
让newShoppingItems=this.calculateShoppingItems();
this.setState({listOfShoppingItems:newShoppingItems});
}
计算hoppingitems(){
let shoppingItemsCart=[]
如果(this.props.milk<3){
让value=“买些牛奶”;
shoppingItemsCart.push(价值);
}
如果(this.props.bread<2){
让value=“买些面包”;
shoppingItemsCart.push(价值);
}
如果(此.props.fruit<10){
让value=“买些水果”;
shoppingItemsCart.push(价值);
}
如果(this.props.juice<2){
让value=“买点果汁”;
shoppingItemsCart.push(价值);
}
如果(this.props.sweets<5){
让value=“买些糖果”;
shoppingItemsCart.push(价值);
}
返回购物项目;
}
render(){
返回(
等
);
}
}
导出默认NotesContainer;
当道具或状态发生更改时,会触发组件更新。如果更改此方法中的状态,将导致无限循环(除非实现shouldComponentUpdate
)
当您收到新道具时,您的状态似乎会发生变化,因此,组件将接收道具
似乎是个好地方。从:
当组件接收新道具时调用。初始渲染时不调用此方法
通过使用this.setState()
更新状态,在调用render()
之前,利用此机会对道具转换作出反应。可以通过此.props访问旧道具。在此函数中调用this.setState()
,将不会触发其他渲染