javascript - 在 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
})
});
}
解决方案
你可以试试这样的。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!"))
}
推荐阅读
- html - 引导对齐不起作用
- kubernetes - Kubernetes:volume.beta.kubernetes.io/storage-class 或 spec.StorageClassName
- jquery - 有没有办法选择动态创建的 CSS 在其他地方显示?
- python - Python Pandas Series.isin 不起作用
- mysql - 每个用户 ID 只获取所有行的总和一次
- jspdf - jspdf autoTable中的动态单元格颜色?
- python - 如何按日期对数据库进行排序?
- angular - 我想使用 Angular 6 上传文件并将其与 API 连接,但它采用默认类型“application/json”,我想将其更改为文件格式
- c - 指向同一个变量的指针数组
- scala - 正则表达式模式相等