首页 > 解决方案 > 在反应状态下更改嵌套数组对象

问题描述

我想替换嵌套数组对象的值,如下所示,当单击按钮时,它将替换 x 索引对象的旧值并在那里设置新值。

class compo extends React.Component {
    constructor() {
        super();
        this.state = {
            tabsData:[
               {
                  id:1,
                  title:"OldTitle1"
               },
               {
                  id:2,
                  title:"OldTitle2"
               }
            ],
        }
        this.changeTab = this.changeTab.bind(this)
    }
    changeTab(){
       const newData={
           id=3,
           title="New One"
       }
       //replace the above new data in the second object of nested array in state
    }
    render(){
        return(
            <button type="button" >Add</button>
        )
    ;}
}
export default compo

之后的状态应该是这样的

tabsData:[
      {
         id:1,
         title:"OldTitle"
      },
      {
         id:3,
         title:"New One"
      }
  ]

标签: arraysreactjsnested

解决方案


你可以做这样的事情......

import React from "react";

class compo extends React.Component {
  constructor() {
    super();
    this.state = {
      tabsData: [
        {
          id: 1,
          title: "OldTitle1"
        },
        {
          id: 2,
          title: "OldTitle2"
        }
      ]
    };
    this.changeTab = this.changeTab.bind(this);
  }
  changeTab() {
    const newData = {
      id: 3,
      title: "New One"
    };
    // Make duplicate since you can't mutatue state
    let newTabData = [...this.state.tabsData];

    const id = 2; // id to be removed

    // CASE 1: If you want to maintain order
    const index = newTabData.findIndex((data) => data.id === id);
    if (index > -1) {
      // replace oldData with newData
      newTabData.splice(index, 1, newData);
    } else {
      // simply add newData at last
      newTabData.push(newData);
    }

    // CASE 2: If order doesn't matter
    // // remove oldData
    // newTabData = newTabData.filter((data) => data.id !== id);
    // // add new data at last
    // newTabData.push(newData);


    // finally update the state irrespective of any case
    this.setState({ tabsData: newTabData });
  }
  render() {
    return (
      <div>
        <button type="button">
          Add
        </button>
        <button type="button" onClick={this.changeTab}>
          Change
        </button>
        <br />
        {JSON.stringify(this.state, null, 2)}
      </div>
    );
  }
}
export default compo;

推荐阅读