【问题标题】:Why does setState cause my React app go into infinite loop?为什么 setState 会导致我的 React 应用程序进入无限循环?
【发布时间】:2021-01-28 16:36:57
【问题描述】:

我正在尝试渲染以下组件,该组件应该采用一些帐户级别值的值并将小计呈现在 div 中。这是代码

import * as React from 'react';
import { ILiquidiManagerProps } from './ILiquidiManagerProps';
import {AccountValue} from './AccountFields';
import {LiquidTEUR} from './DummyContent';

interface SubtotalState {
    Account?: any,
    SubtotalValue?: any
  }

export default class SubtotalValues extends React.Component<ILiquidiManagerProps, SubtotalState> {
    public constructor(props: ILiquidiManagerProps) {
        super(props);
        this.state = {
            Account: LiquidTEUR.Subcategories.find(item => item.Name == this.props.label),
            SubtotalValue: 0
        }
    }
    
    private getText = data => {
        this.setState({SubtotalValue: data});
    }

    private initiateValue = () => {
        let Account = this.state.Account;
        let subtotal = 0;
        Account.Accounts.map((item) => {
            subtotal += item.Value;
        })
        this.setState({SubtotalValue: subtotal});
    }

    public render(): React.ReactElement<ILiquidiManagerProps> {
        this.initiateValue();
        return(
            <React.Fragment>
            <a className="collapsible" href="#">
                <div 
                    className={`p-2 text-right value ` + this.props.bgColor + ` font-weight-bold ` + this.props.textColor}
                    data-date={this.props.date}
                    data-name={this.props.label}
                >{this.state.SubtotalValue}</div></a>
            <div className="content hidden">
                {this.state.Account.Accounts.map((item, key) => {
                    return <AccountValue key={key} label={item.Value} getValue={this.getText} subtotal={this.state.SubtotalValue} />;
                })}
                <span className="add-pos">&nbsp;</span>
            </div>
            </React.Fragment>
        );
    }
}

这是它生成的错误消息

未捕获(承诺)不变违规:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制了嵌套更新的数量以防止无限循环。

我尝试了几种不同的方法来设置小计的状态,但我似乎总是遇到同样的错误,而且我不确定我在哪里导致了无限循环。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:
    1. 组件渲染时调用this.initiateValue
    2. initiateValue 设置状态
    3. 设置状态触发渲染
    4. 转到 1

    可能想改为从componentDidMount 调用initiateValue

    (或者切换到编写一个函数组件并将其放入useEffect钩子中)。

    【讨论】:

      【解决方案2】:

      你不应该在渲染方法中使用setState(),因为你正在使用this.initiateValue();

      因为正如您所知,每当 setState() 被调用时,就会发生重新渲染,这就是它无限运行的原因。

      如果要在componentDidMount()useEffect()内部初始化数据调用

      更多了解可以参考Calling setState() in React from render method

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-13
        • 1970-01-01
        • 2011-08-13
        • 2020-06-04
        • 1970-01-01
        • 2023-03-22
        • 2013-06-17
        • 1970-01-01
        相关资源
        最近更新 更多