javascript - ComponentDidUpdate 不起作用

标签 javascript reactjs

我正在尝试使用componentDidUpdate动态渲染组件集合。 这是我的场景:

var index = 0;

class myComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      componentList: [<ComponentToRender key={index} id={index} />]
    };

    this.addPeriodHandler = this.addPeriodHandler.bind(this);
  }

  componentDidUpdate = () => {
    var container = document.getElementById("container");
    this.state.componentList.length !== 0
      ? ReactDOM.render(this.state.componentList, container)
      : ReactDOM.unmountComponentAtNode(container);
  };

  addHandler = () => {
    var array = this.state.componentList;
    index++;
    array.push(<ComponentToRender key={index} id={index} />);
    this.setState = {
      componentList: array
    };
  };

  render() {
    return (
      <div id="Wrapper">
        <button id="addPeriod" onClick={this.addHandler}>
          Add Component
        </button>
        <div id="container" />
      </div>
    );
  }
}

问题是 componentDidUpdate 只能工作一次,但每次该组件的状态发生变化时它都应该工作。 预先感谢您。

最佳答案

这不是如何使用react。使用ReactDOM.render(),您正在创建一个全新的组件树。通常,您只需执行一次即可最初渲染您的应用程序。其他所有内容都将由组件的 render() 函数渲染。如果你使用 ReactDOM.render() 来做到这一点,你基本上会丢弃每次更新数据时已经渲染的所有 React 内容,并从头开始重新创建它,而实际上你可能只需要添加一个节点某处。

此外,您实际存储在组件状态中的内容应该是纯数据而不是组件。然后使用此数据在 render() 函数中渲染组件。

有效用例示例:

class MyComponent extends Component{
        state = {
            periods: []
        };

        handleAddPeriod = () => {
            this.setState(oldState => ({
                periods: [
                    ...oldState.periods,
                    {/*new period data here*/}
                ],
            });
        };

        render() {
            return (
                <div id="Wrapper">                                 
                    <button id="addPeriod" onClick={this.handleAddPeriod}>
                        Add Component
                    </button>
                    <div id="container">
                        {periods.map((period, index) => (
                            <ComponentToRender id={index} key={index}>
                                {/* render period data here */}
                            </ComponentToRender>
                        ))}
                    </div>
                </div>
            );
        }
    }
}

此外,您不应该像使用 index 那样使用全局变量。如果您的数据在使用应用程序期间发生变化,则这应该是组件状态的指示器。

关于javascript - ComponentDidUpdate 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51635554/

相关文章:

javascript - 使用输入类型按钮更新数据

javascript - 如何更新组件安装路径?

reactjs - 在下拉列表中设置重置按钮

javascript - 如何从React Native的ReactActivity发送 Intent 数据到Javascript

javascript - 在 React App 中触发合成事件

javascript - JavaScript 中的字符串到整数对象散列

javascript - 如何为每个对象添加Javascript函数?

javascript - <span> onclick 事件未触发

reactjs - undefined 不是一个对象(评估 'userCredentails.user' )

javascript - 控制选择框内所选值的显示方式 : Is there a way to render the selected item separately?