简体   繁体   中英

How to push new column into array using setState

I am using an external library to build a Taskboard and what I want to achieve is to add a new column when clicking and add column button. I am struggling with adding the column, I have the newly created column but it doesn't get added to the array. What am I doing wrong and how can I insert the newly created column? Here is my code:


  onAddColumn = () => {
    const newColumn: TaskBoardColumnModel = {
      id: this.state.columnsData.length + 1,
      title: 'New Column',
      status: 'new',
      edit: true,
    };

    console.log(this.state.columnsData);

    this.setState({
      columsData: newColumn,
    });
    console.log(this.state.columsData);
  };
}

Your main issue is the way you update your state. This is what you have:

this.setState({
      columsData: newColumn,
    });

This piece of code will set the state to columsData: newColumn , which is wrong for a few reasons:

  • columsData should be columnsData
  • Your piece of code will remove all the other columns and replace it with only one. Which will fail the code because columnsData will become an object and not an array

Here is what it should be:

this.setState({
      columnsData: [...this.state.columnsData, newColumn],
    });

This will keep your current state, and add the new column to your existing list.

You have a typo in columsData . Additionally columnsData should be an array so you probably need to set the new state to the old one plus the new column.

eg something like:

this.setState({
    columnsData: [...this.state.columnsData, newColumn],
});

 this.setState({ if(this.state.columnsData && this.state.columnsData.length>0) { columnsData: [...this.state.columnsData, newColumn], } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM