简体   繁体   English

React componentsDidUpdate与SetState回调

[英]React componentsDidUpdate vs SetState callback

If I run this code I get infinite loop in componentDidMount , adding if statement in (prevState !== this.state) doesn't help neither. 如果我运行这段代码,我会在componentDidMount陷入无限循环,在(prevState !== this.state)中添加if语句对(prevState !== this.state)都没有帮助。

state = {
    purchaseable: false,
    totalPrice: 0
  }

  updatePurchaseState = () => ({
      purchaseable: true
    });

  addIngredientHandler = (type) => {
    const newPrice = totalPrice + 1
    this.setState({
      totalPrice: newPrice
    });
  }

  componentDidUpdate (prevProps, prevState) {
    this.updatePurchaseState()
  }

But if I execute updatePurchaseState in setState callback everything works fine: 但是,如果我在setState回调中执行updatePurchaseState ,则一切正常:

addIngredientHandler = () => {
    let newPrice = newPrice +1
    this.setState(() => ({
      totalPrice: newPrice
    }), () => this.updatePurchaseState());
  }

According to React documentation https://reactjs.org/docs/react-component.html#setstate componentDidUpdate is preferable way to execute updatePurchaseState . 根据React文档https://reactjs.org/docs/react-component.html#setstate componentDidUpdate是执行updatePurchaseState首选方法。

Why componentDidUpdate runs into infinite loop but setState callback doesn't if both update state and should re-render? 为什么componentDidUpdate陷入无限循环,但是setState回调如果同时更新状态并应重新呈现,则不会返回? What is the best approach for calling updatePurchaseState ? 调用updatePurchaseState的最佳方法是updatePurchaseState

Every time you update your component's state or props, the component will re-render and invoke componentDidUpdate . 每次更新组件的状态或道具时,组件将重新渲染并调用componentDidUpdate So both functions addIngredientHandler and updatePurchaseState will trigger componentDidUpdate to be called. 因此,两个函数addIngredientHandlerupdatePurchaseState都会触发componentDidUpdate被调用。 In componentDidUpdate you try to call updatePurchaseState again, causing an infinite loop. componentDidUpdate您尝试再次调用updatePurchaseState ,从而导致无限循环。

The way to do it correctly is that in componentDidUpdate , you have to check if updatePurchaseState should be called or not, by comparing current state with previous state: 正确执行此操作的方法是在componentDidUpdate ,您必须通过将当前状态与先前状态进行比较来检查是否应调用updatePurchaseState

  componentDidUpdate (prevProps, prevState) {
    if (this.state.purchaseable !== prevState.purchaseable) {
      this.updatePurchaseState()
    }
  }

Please read the official document of React for more details 请阅读React的官方文档以获取更多详细信息

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

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