gpt4 book ai didi

javascript - 在 react 中更新状态时递归太多

转载 作者:数据小太阳 更新时间:2023-10-29 05:57:31 25 4
gpt4 key购买 nike

在此示例中,当我尝试在 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)。

当你收到新的 Prop 时,你的状态看起来会发生变化,因此 componentWillReceiveProps 似乎是个好地方。来自docs :

Invoked when a component is receiving new props. This method is not called for the initial render.

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.

关于javascript - 在 react 中更新状态时递归太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32198502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com