在此示例中,当我尝试在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;
componentDidUpdate
当 props 或 state 改变时触发。如果您更改此方法中的状态,则会导致无限循环(除非您实现shouldComponentUpdate
).
当你收到新的道具时,你的状态看起来会发生变化,因此componentWillReceiveProps
看来是个好地方。来自docs https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops:
当组件接收新的 props 时调用。初始渲染不会调用此方法。
以此为契机,在之前对道具转换做出反应render()
通过使用更新状态来调用this.setState()
。旧的 props 可以通过 this.props 访问。呼唤this.setState()
此函数内不会触发额外的渲染。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)