首页 > 解决方案 > 如何修复 TypeError:this.state 为空?

问题描述

我正处于 react.js 的学习阶段,我试图通过单击按钮来复制整个 div。我需要在哪里更改代码中的状态。相应的按钮也应该相应地。添加按钮以添加 div。删除按钮以删除添加的 div。

      class ReplicateDiv extends React.Component {
      constructor(props) {
      super(props);

      this.state = { array: [] };
      this.manageDiv = this.manageDiv.bind(this);
       }
      manangeDiv(e, type) {


        const { array } = this.state.array;

        if (type === "add") {
          array.push(array[0]);
        } else if (type === "remove") {
          array.splice(0, 1);
        }
        this.setState({
          array
        });
      }

      render() {
        return (
          <div>
            <button type="button" onClick={e => this.manangeDiv(e, "add")}>
              add
            </button>
            <button type="button" onClick={e => this.manangeDiv(e, "remove")}>
              remove
            </button>
            {this.state.array.map((item, index) => {
              return <div key={index}> Dynamic Div </div>;
            })}
          </div>
        );
      }
    }
    ```

标签: reactjs

解决方案


constructor你需要初始化状态变量。

constructor(props) {

    super(props);

    this.state = {array: [] };

  }

推荐阅读