在反应状态下更改嵌套数组对象

时间:2021-03-30 11:05:19

标签: arrays reactjs nested

我想像下面这样替换嵌套数组对象的值,当单击按钮时,它将替换 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"
      }
  ]

2 个答案:

答案 0 :(得分:1)

无法发表评论,因为我的代表不到 50 人......基于您在这里需要的是代码的想法。

https://codesandbox.io/s/brave-lumiere-dh9ry?file=/src/App.js

const [data, setData] = React.useState([
    {
      id: 1,
      title: "OldTitle1"
    },
    {
      id: 2,
      title: "OldTitle2"
    }
  ]);
  const newData = { id: 3, title: "New One" };

  const addData = () => {
    const newArr = data;
    newArr[1] = newData;
    console.log("newArr>>>>", newArr);
    setData([...newArr]);
  };

答案 1 :(得分:1)

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

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;