简体   繁体   中英

Push objects into an array in reactjs

I'm getting a list of objects as a response like this

在此处输入图像描述

As you can see the objects are not in an array. I want to push these objects into an array. I tried the following way

this.setState({
   countrydata: this.state.countrydata.push(datasnapshot.val()),
})

But it didn't work. What's the correct approach to push these objects into an array?

PS:

componentDidMount() {
        const countryCode = this.props.match.params.countryCode;
        var countryName = getName(countryCode);
        var firebaseHeadingref = firebase.database().ref(countryCode);
        firebaseHeadingref.once('value').then(datasnapshot => {
            this.setState({
                countrydata: datasnapshot.val(),
                countryName: countryName,
                loading: false
            })
        });
    }

You could try something like this. Array.prototype.push() . I have not tested below code.


componentDidMount=async() =>{
        const countryCode = this.props.match.params.countryCode;
        var countryName = getName(countryCode);
        var firebaseHeadingref = firebase.database().ref(countryCode);
       const datasnapshot = await firebaseHeadingref.once('value');

  this.setState(prevState=>{
   ...prevState,
    countryName,
    countrydata: [...prevState.countrydata, datasnapshot.val()],
    loading: false,
  },()=>console.log("done!"))


    }



I think that the "countrydata" in a dict not an array. Try to initialize the it as an empty array.

Array.prototype.push returns the new length of the array after the push, so you are essentially setting the state to a number.

You are not allowed to mutate the array with React state, you need to create a new array containing your new elements:

// When updating state based on current state, use the function form of setState.
this.setState(state => {
   countrydata: [...state.countrydata, datasnapshot.val()],
})

This is assuming countryData is indeed an array, which from your screenshot, it appears to not (it seems to be an object), so you may be set something wrong somewhere along the way (or datasnapshot.val() ) doesn't contain what you think it contains.

Use for-in to loop through the object or use Object.keys() .

const data = datasnapshot.val();
const countrydata = [];

for (let key in data) {
  countrydata.push(data[key])
}

// using Object.keys()

Object.keys(data).forEach((key) => countrydata.push({ [key]: data[key]}))

this.setState({
  countrydata
})

 const data = { place1: { name: 'One'}, place2: { name: 'Two'}, place3: { name: 'Three'}, }; const countrydata = []; for (let key in data) { countrydata.push({ [key]: data[key] }); } console.log(countrydata);

You could do this:

const keys = Object.keys(countryData);  // array of the keys ["place_1", ...]
const array = Array(keys.length);       // Prepares the output array of the right size
for (let i=0; i<keys.length; i++) {
  const country = countryData[keys[i]]; // get the next country object
  country.key = keys[i];                // add the key into the object if you need it
  array[i] = country;                   // store the value into the array at index 'i'
}
// array now is [ {key: "place_1", description: "Sigiriya Rock Fortress"}, ...]
this.setState({countryDataArray: array});

You need to convert the response data from firebase to an array like this:

componentDidMount() {
  const countryCode = this.props.match.params.countryCode;
  var countryName = getName(countryCode);
  var firebaseHeadingref = firebase.database().ref(countryCode);
  firebaseHeadingref.once('value').then(datasnapshot => {

    const countryData = datasnapshot.val();

    const countryDataArray = [];

    for (const key in countryData) {
      countryDataArray.push({ key, ...countryData[key]});
    }

    this.setState({
      countrydata: countryDataArray,
      countryName: countryName,
      loading: false
    })
  });
}

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