在更新状态时更新递归过多 [英] Too much recursion when updating state in react

查看:60
本文介绍了在更新状态时更新递归过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个例子中,当我尝试在 componentDidUpdate 生命周期回调期间更新状态时,我得到一个过多的递归错误。我应该如何更新州?

In this example, when I try to update the state during the componentDidUpdate life cycle callback, I get a too much recursion error. How should I be updating the state?

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;


推荐答案

componentDidUpdate 。如果更改此方法中的状态,则会导致无限循环(除非您实现 shouldComponentUpdate )。

componentDidUpdate is triggered when either the props or the state has changed. If you change the state in this method, you are causing an infinite loop (unless you implement shouldComponentUpdate).

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

It looks like your state changes when you receive new props, therefore componentWillReceiveProps seems a good place. From the docs:


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

Invoked when a component is receiving new props. This method is not called for the initial render.

使用此方法作为在 render() this.setState()更新状态来调用$ c>。可以通过this.props访问旧道具。在此函数中调用 this.setState()将不会触发额外的渲染。

Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.

这篇关于在更新状态时更新递归过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆