简体   繁体   中英

How to insert data in array in react js?

I'm using react.js and I have class base component. Now the scenario is. I have one array with the name of partitions.

partitions=["P1","P2","P3"]

and I have another array with the name dayDetails which is null at the start.

When my components mounts. I map partitions array and add an object in dayDetail array. Number of elements in partition array will be the number of objects put in the dayDetail array. Now the problem is only One object is putting in the dayDetail but it suppose to add three because number of partitions are 3.

here is my code below.

import React from "react";

class Step2 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        partitions:["P1","P2","P3"],
        dayDetails:[],

    };
  }


  componentDidMount() {
    this.setTimePriceNullJson()
  }

  setTimePriceNullJson = () => {
    {this.state.partitions.map((item,index)=>( 
       this.setState({dayDetails:[...this.state.dayDetails,
        {
          "partitionIndex":index,
          "timings":[
              {"name":"sunday"}
          ],
          "pricings":[
              {"name":"sunday"}
          ]
        }
        
      ]})
    )
    )}
    
  }

  componentDidUpdate(){
    console.log("--> ",this.state.dayDetails)

  }


  render() {
    return (
      <div style={styles.main_container}>
        ...
      </div>
    )
  }
}

export default Step2;

Right now output is coming: this.state.dayDetail output is:

[{"partitionIndex": 2, "pricings": [[Object]], "timings": [[Object]]}]

Desire output is:

[
{"partitionIndex": 0, "pricings": [[Object]], "timings": [[Object]]},
{"partitionIndex": 1, "pricings": [[Object]], "timings": [[Object]]},
{"partitionIndex": 2, "pricings": [[Object]], "timings": [[Object]]}
]

Just do everything step by step. It will be much shorter and easier to read.

setTimePriceNullJson = () => {
  const dayDetails = this.state.partitions.map((x, i) => {
    return {
      partitionIndex: i,
      timings: [{ name: "sunday" }],
      pricings: [{ name: "sunday" }]
    };
  });
  this.setState({ ...this.state, dayDetails: dayDetails });
};

Clarifications: setState is not reflecting changes to the state object immediatelly, in each iteration of map function state.dayDetails was an empty array, so...this.state.dayDetails was always [], and thats why only last value was set there.

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