Javascript 功能执行后未设置反应道具

Javascript 功能执行后未设置反应道具,javascript,reactjs,Javascript,Reactjs,我有一个react burger builder组件,您可以在其中向汉堡添加配料。这是我到目前为止的设置 const INGREDIENT_PRICES = { salad: 5, cheese: 10, meat: 20, bacon: 10 } class BurgerBuilder extends Component { state = { ingredients: { salad: 0, bacon:

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

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方法,以更新页面上汉堡的视图

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

现在不更新,只要调用
this.updatePurchaseState
方法,我就使用chrome开发工具来识别问题

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

React正在等待您是否再次调用
setState
。 您需要使用回调函数

this.setState(
    {totalPrice: newPrice, ingredients: updatedIngredients}, 
    () => this.updatePurchaseState()
);
从:
setState()
并不总是立即更新组件。它可以批处理更新或将更新推迟到以后。这使得调用
setState()
后立即读取
This.state
成为一个潜在的陷阱。相反,使用
componentdiddupdate
或setState回调(
setState(updater,callback)
),这两种回调都保证在应用更新后触发。如果需要基于上一个状态设置状态,请阅读下面的updater参数


这很有效,谢谢你。这是否总是适用?在实际执行函数之前,是否需要再次调用函数以更新状态?@baileyhaldwin是的,还要检查对我添加的文档的引用。