gpt4 book ai didi

javascript - 函数执行后没有设置 react Prop

转载 作者:行者123 更新时间:2023-11-30 11:11:59 25 4
gpt4 key购买 nike

我有一个 React 汉堡生成器组件,您可以在其中向汉堡添加配料。这是我到目前为止的设置。

const INGREDIENT_PRICES = {
salad: 5,
cheese: 10,
meat: 20,
bacon: 10
}


class BurgerBuilder extends Component {
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0
},
totalPrice: 30,
purchaseble: false
}
}

因此,对于添加的每个项目,状态以及在顶部定义的价格都会更新。

我有一个处理程序可以像这样向汉堡添加配料:

addIngredientHandler = (type) => {
const oldCount = this.state.ingredients[type];
const updatedCount = oldCount +1;
const updatedIngredients = {
...this.state.ingredients
};
updatedIngredients[type] = updatedCount;
const priceAddition = INGREDIENT_PRICES[type];
const newPrice = this.state.totalPrice + priceAddition
this.setState({totalPrice: newPrice, ingredients: updatedIngredients})
this.updatePurchaseState();
}

这会更新 BurgerBuilder 组件状态中的成分。然后触发 render 方法,更新页面上汉堡的 View 。

此外,我有一个 updatePurchaseState,用于启用和禁用按钮以提交购买。

现在不更新,每当this.updatePurchaseState方法被调用所以我使用chrome dev工具来确定问题。

Here is the debugger at first, where the salad-ingredient is added one to the state, as it should, and then updating the state

Here is the debugger, when diving into the updatePurchaseState function, but without the updated state

为什么在第一次函数调用后状态没有更新?

最佳答案

React 正在等待您是否再次调用 setState

你需要使用回调

this.setState(
{totalPrice: newPrice, ingredients: updatedIngredients},
() => this.updatePurchaseState()
);

来自react docs :

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

关于javascript - 函数执行后没有设置 react Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53304655/

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