首页 > 解决方案 > 在 reactjs 中将对象推送到数组中

问题描述

我得到一个对象列表作为这样的响应

在此处输入图像描述

如您所见,对象不在数组中。我想将这些对象推入一个数组。我尝试了以下方式

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

但它没有用。将这些对象推入数组的正确方法是什么?

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
            })
        });
    }

标签: javascriptarraysreactjs

解决方案


你可以试试这样的。Array.prototype.push()。我没有测试下面的代码。


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!"))


    }




推荐阅读