在更新状态时更新递归过多 [英] Too much recursion when updating state in react
问题描述
在这个例子中,当我尝试在 componentDidUpdate
生命周期回调期间更新状态时,我得到一个过多的递归
错误。我应该如何更新州?
In this example, when I try to update the state during the componentDidUpdate
life cycle callback, I get a too much recursion
error. How should I be updating the state?
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;
推荐答案
componentDidUpdate $ c当道具或状态发生变化时触发$ c>。如果更改此方法中的状态,则会导致无限循环(除非您实现
shouldComponentUpdate
)。
componentDidUpdate
is triggered when either the props or the state has changed. If you change the state in this method, you are causing an infinite loop (unless you implement shouldComponentUpdate
).
当你收到新的道具时,你的状态会发生变化,因此 componentWillReceiveProps
似乎是一个好地方。来自 docs :
It looks like your state changes when you receive new props, therefore componentWillReceiveProps
seems a good place. From the docs:
组件接收新道具时调用。初始渲染不会调用此方法。
Invoked when a component is receiving new props. This method is not called for the initial render.
使用此方法作为在 render()$ c之前对prop转换作出反应的机会通过使用
this.setState()
更新状态来调用$ c>。可以通过this.props访问旧道具。在此函数中调用 this.setState()
将不会触发额外的渲染。
Use this as an opportunity to react to a prop transition before render()
is called by updating the state using this.setState()
. The old props can be accessed via this.props. Calling this.setState()
within this function will not trigger an additional render.
这篇关于在更新状态时更新递归过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!