【问题标题】:ReactJs: Rendering on state change getting into infinite loopReactJs:渲染状态变化进入无限循环
【发布时间】:2021-01-16 20:19:33
【问题描述】:

这里我试图在兄弟组件 A 和 B 之间传递数据,我想在组件 A 中的异步事件完成后重新渲染组件 B。

    class ParentComponent extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                valueKey: '',
            };
        }
    
        parentFunction(dataFromChild) {
            this.setState({ valueKey: dataFromChild });
        }
        render() {
            const { valueKey } = this.state;
            
            return (
                <div>
                    <componentA
                      url={url}
                      ...
                      functionCallFromParent={() => this.parentFunction()}
                    />
                    <componentB valueFromParent={valueKey} />
                </div>
            );
        }
    }

class componentA extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            items: null,
        };
        // asynchronous request made to server which updates the state when response received.
        this._getTiles();
    }

render() {
        const { items } = this.state;
        

        if (items && items.asArray().length > 0) {
            functionCallFromParent('Hello From Child1');
            return (
                <div>
                    {tiles}
                </div>
            );
        }

        return null;
    }
}

问题是,每次 componentA 调用 functionCallFromParent() ParentComponent 的渲染都会执行,它会重新渲染 componentA 和 componentB 并且这个循环继续。然而,我只希望在 componentA 要求时重新渲染 componentB。

【问题讨论】:

  • 你应该在异步代码部分(大概是_getTiles)中调用functionCallFromParent,而不是在渲染函数中
  • @maya_nk99 但我没有按钮单击或任何用户事件。组件 B 需要在组件 A 中发生的异步事件完成后重新渲染
  • 如果 asArray() 是 Javascript 中的一个函数?我认为它是在 Python 中
  • 每次设置状态时,都会导致使用该状态的组件重新渲染。所以它导致了无限循环。

标签: javascript reactjs react-redux jsx


【解决方案1】:

functionCallFromParent() 被放在 render() 中的 ComponentA 中,这意味着每次渲染/重新渲染组件时都会调用它,这种情况经常发生!当这种情况发生时,ParentComponent.parentFunction() 将被调用来设置它自己的状态,这反过来会导致它自己和它自己的孩子重新渲染,这就是循环的创建方式。您应该将其移至收到响应的代码部分。

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2016-02-29
    • 1970-01-01
    • 2010-12-24
    • 2023-02-03
    • 2020-08-07
    • 1970-01-01
    • 2021-02-15
    • 2018-06-09
    相关资源
    最近更新 更多