React - remove nested array item using setState function call

后端 未结 3 523
再見小時候
再見小時候 2021-01-27 06:39

I am trying to remove a (semi) deeply nested item from an array using setState but it doesn\'t seem to be working. My state is structured as follows:

state = {
         


        
3条回答
  •  遥遥无期
    2021-01-27 06:54

    My recommendation would be to use .map to make things are bit easier to digest. You can then write it like so:

    onRemoveModelElementClick = (rowId, modelElementId) => {
      const updatedRowsState = this.state.rows.map(row => {
        // this is not the row you're looking for so return the original row
        if (row.id !== rowId) {
          return row;
        }
    
        const filteredSeries = row.series.filter(s => s.id !== modelElementId);
        return {
          // spread properties (id, node, series)
          ...row,
          // overwrite series with item filtered out
          series: filteredSeries,
        };
      });
    
      // since rest of the state doesn't change, we only need to update rows property
      this.setState('rows', updatedRowsState);
    }
    

    Hope this helps and let me know if you have any questions.

提交回复
热议问题