繁体   English   中英

React componentsDidUpdate与SetState回调

[英]React componentsDidUpdate vs SetState callback

如果我运行这段代码,我会在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()
  }

但是,如果我在setState回调中执行updatePurchaseState ,则一切正常:

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

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

为什么componentDidUpdate陷入无限循环,但是setState回调如果同时更新状态并应重新呈现,则不会返回? 调用updatePurchaseState的最佳方法是updatePurchaseState

每次更新组件的状态或道具时,组件将重新渲染并调用componentDidUpdate 因此,两个函数addIngredientHandlerupdatePurchaseState都会触发componentDidUpdate被调用。 componentDidUpdate您尝试再次调用updatePurchaseState ,从而导致无限循环。

正确执行此操作的方法是在componentDidUpdate ,您必须通过将当前状态与先前状态进行比较来检查是否应调用updatePurchaseState

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

请阅读React的官方文档以获取更多详细信息

暂无
暂无

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

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