【问题标题】:Too much recursion when updating state in react在反应中更新状态时递归过多
【发布时间】:2015-08-25 07:55:58
【问题描述】:

在此示例中,当我尝试在 componentDidUpdate 生命周期回调期间更新状态时,我收到 too much recursion 错误。我应该如何更新状态?

import React from 'react';

class NotesContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { listOfShoppingItems: [] };
  }

  componentDidUpdate(nextProps, nextState) {
    let newShoppingItems = this.calculateShoppingItems();
    this.setState({ listOfShoppingItems: newShoppingItems });
  }

  calculateShoppingItems() {
    let shoppingItemsCart = []

    if (this.props.milk < 3) {
      let value = "Buy some milk";
      shoppingItemsCart.push(value);
    }

    if (this.props.bread < 2) {
      let value = "Buy some bread";
      shoppingItemsCart.push(value);
    }

    if (this.props.fruit < 10) {
      let value = "Buy some fruit";
      shoppingItemsCart.push(value);
    }

    if (this.props.juice < 2) {
      let value = "Buy some juice";
      shoppingItemsCart.push(value);
    }

    if (this.props.sweets < 5) {
      let value = "Buy some sweets";
      shoppingItemsCart.push(value);
    }

    return shoppingItemsCart;
  }

  render() {
    return (
      <div>
        Etc...
      </div>
    );
  }
}

export default NotesContainer;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    componentDidUpdate 在 props 或 state 发生变化时触发。如果您在此方法中更改状态,则会导致无限循环(除非您实现shouldComponentUpdate)。

    当您收到新的道具时,您的状态似乎发生了变化,因此componentWillReceiveProps 似乎是个好地方。来自docs

    在组件接收新道具时调用。初始渲染不调用此方法。

    在通过使用this.setState() 更新状态来调用render() 之前,将此作为对道具转换作出反应的机会。可以通过 this.props 访问旧的道具。在此函数中调用 this.setState() 不会触发额外的渲染。

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2018-01-13
      • 2022-01-23
      相关资源
      最近更新 更多