繁体   English   中英

调用this.setState后函数变量值重置

[英]Function variable value resetting after calling this.setState

我对 JavaScript 世界比较陌生,我正在学习 react 并且遇到了一个奇怪的问题,请参阅此代码

addIngredientHandler = (type) => {

    let oldCount  = this.state.ingredients[type];
    let copyState = {...this.state.ingredients};

    let newPrice = 0;

    copyState[type] = oldCount + 1;

    this.setState( (prevState, prevProps) => {

        newPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];

        newPrice =  Math.round(newPrice * 100) / 100;

        console.log('newprice inside setState: ' + newPrice);
        
        return { ingredients: copyState, totalPrice:  newPrice}
        

    } );

    console.log('newprice outside setState: ' + newPrice);

    this.updatePurchaseable(copyState, newPrice);


}

在这里,我关心的是 newPrice 变量,它用于在添加更多项目时更新状态,它工作正常

问题是在这个之后。 setState返回 newPrice 再次被重新测试为 0,所以我不能将它用于底部的函数。

是的,我可以直接使用状态变量,但由于setState执行的 asnyc 性质,我想改为传递变量值。

在控制台中,您可以看到由于setState异步性质,首先执行外部控制台日志,然后执行内部控制台日志

在此处输入图片说明

也许我没有得到一些正在产生这种行为的生命周期反应。

这是状态值,这些值应该无关紧要,但仍然是为了更好的画面

state = {
    ingredients: {
        salad: 0,
        bacon: 0,
        meat: 0,
        cheese: 0,
    },
    purchasable: false,

    totalPrice: 0

}

任何提示都有帮助,感谢阅读。

调用setStatenewPrice等于0的原因是因为 React 状态更新是异步的 状态更新后的代码会setState实际做某事之前运行,所以在调用this.updatePurchaseable(copyState, newPrice);的阶段this.updatePurchaseable(copyState, newPrice); newPrice所有计算尚未执行。

顺便说一句- 这也是为什么您的console.log以“相反”顺序打印的原因,每次渲染外部日志都在内部日志之前打印。

对于这个特定的代码示例,我建议您尝试将现在在setState回调中的所有计算移到它之外,甚至移到不同的函数中。

试试这个 -

calculateNewPrice = (totalPrice, type) => {
    newPrice = totalPrice + PRICES_OF_INGREDIENTS[type];
    newPrice =  Math.round(newPrice * 100) / 100;
}

addIngredientHandler = (type) => {
    const { totalPrice } = this.state;
    
    let oldCount  = this.state.ingredients[type];
    let copyState = {...this.state.ingredients};
    copyState[type] = oldCount + 1;

    const newPrice = calculateNewPrice(totalPrice, type);

    this.setState({ ingredients: copyState, totalPrice:  newPrice });
    
    this.updatePurchaseable(copyState, newPrice);
}

this.setState()被异步调用,所以你不能依赖this.state在调用this.setState()后立即引用更新的值。 阅读有关组件状态常见问题解答

如果要在状态更新后引用newPrice的更新值,可以:

  1. 使用componentDidUpdate()生命周期方法 请参阅https://reactjs.org/docs/react-component.html#componentdidupdate
addIngredientHandler = (type) => {
  let oldCount = this.state.ingredients[type];
  let copyState = { ...this.state.ingredients };

  let newPrice = 0;

  copyState[type] = oldCount + 1;

  this.setState((prevState) => {
    newPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];
    newPrice = Math.round(newPrice * 100) / 100;

    return { ingredients: copyState, totalPrice: newPrice }
  });
}

componentDidUpdate(prevProps, prevState) {
  if (prevState.totalPrice !== this.state.totalPrice) {
    this.updatePurchaseable(this.state.ingredients, this.state.totalPrice);
  }
}
  1. 使用this.setState()的第二个参数 请参阅https://reactjs.org/docs/react-component.html#setstate 上的文档。
addIngredientHandler = (type) => {
  let oldCount = this.state.ingredients[type];
  let copyState = { ...this.state.ingredients };

  let newPrice = 0;

  copyState[type] = oldCount + 1;

  this.setState((prevState) => {
    newPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];
    newPrice = Math.round(newPrice * 100) / 100;

    return { ingredients: copyState, totalPrice: newPrice }
  }, () => {
    this.updatePurchaseable(this.state.ingredients, this.state.totalPrice);
  });
}
  1. 使用ReactDOM.flushSync() 请参阅https://github.com/reactwg/react-18/discussions/21
import { flushSync } from 'react-dom';

addIngredientHandler = (type) => {
  let oldCount = this.state.ingredients[type];
  let copyState = { ...this.state.ingredients };

  let newPrice = 0;

  copyState[type] = oldCount + 1;

  flushSync(() => {
    this.setState((prevState) => {
      newPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];
      newPrice = Math.round(newPrice * 100) / 100;

      return { ingredients: copyState, totalPrice: newPrice }
    });
  });

  this.updatePurchaseable(copyState, newPrice);
}

如果我要编写此方法,我会建议使用componentDidUpdate生命周期方法,因为这将确保在总价格发生变化时始终调用updatePurchaseable 如果您只在事件处理程序中调用updatePurchaseable ,那么如果价格在该处理程序之外发生变化,您最终可能会遇到错误。

addIngredientHandler = (type) => {
  this.setState(prevState => {
    let totalPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];
    totalPrice = Math.round(totalPrice * 100) / 100;

    return {
      ingredients: {
        ...prevState.ingredients,
        [type]: prevState.ingredients[type] + 1,
      },
      totalPrice,
    };
  });
}

componentDidUpdate(prevProps, prevState) {
  const { totalPrice, ingredients } = this.state;

  if (prevState.totalPrice === totalPrice) {
    /*
    
    Bail early. This is a personal code style preference. It may 
    make things easier to read as it keeps the main logic on the 
    "main line" (un-nested / unindented)
    
    */
    return;
  }

  /*

  If `updatePurchaseable` is a class method then you don't need to
  pass state to it as it will already have access to `this.state`.

  If `updatePurchaseable` contains complicated business logic,
  consider pulling it out into its own module to make it easier 
  to test.
  
  */
  this.updatePurchaseable(ingredients, totalPrice);
}

React 状态更新是异步的,setState函数是完全同步的,所以当你调用updatePurchaseablenewPrice还没有更新。 将所有额外的“状态更新后”逻辑移动到componentDidUpdate生命周期方法中,以便您可以访问/引用更新的totalPrice并使用更新的状态调用updatePurchaseable

componentDidUpdate(prevProps, prevState) {
  if (prevState.totalPrice !== this.state.totalPrice) {
    const { ingredients, totalPrice } = this.state;
    console.log('newprice outside setState: ' + totalPrice);

    this.updatePurchaseable(ingredients, totalPrice);
  }
}

addIngredientHandler = (type) => {
  this.setState((prevState, prevProps) => {
    let newPrice = prevState.totalPrice + PRICES_OF_INGREDIENTS[type];
    newPrice =  Math.round(newPrice * 100) / 100;
    return {
      ingredients: {
        ...prevState.ingredients,
        [type]: prevState.ingredients[type] + 1,
      }, 
      totalPrice:  newPrice
    }
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM