[英]Adding to object that contains an array an object in state in React
Hello I am building an app that renders a table that receives data from an API.您好,我正在构建一个应用程序,该应用程序呈现一个从 API 接收数据的表。
I am using for the table MDBReact and I am having a hard time adding rows to the table.我正在使用表 MDBReact 并且我很难向表中添加行。
In this.state I have an object datatable that contains an array names rows and I would like to add objects to this array.在 this.state 中,我有一个对象数据表,其中包含一个数组名称行,我想将对象添加到这个数组中。
This is the code and what I have tried but it does not work.这是代码和我尝试过的,但它不起作用。
The problem is in the this.setState, how should I write the adding of an object to an array contained in the datatable object.问题出在 this.setState 中,我应该如何将对象添加到数据表对象中包含的数组中。 Thanks谢谢
import React, { useState } from 'react';
import { MDBDataTableV5 } from 'mdbreact';
import axios from 'axios';
class ListaMesaje extends React.Component {
componentDidMount() {
axios.get(`http://localhost/spv/react-php/src/server.php`)
.then(res => {
const persons = res.data;
for(var i = 0; i < 3; i++) {
this.setState({datatable:{...this.state.datatable,rows:persons.mesaje[i]}})
}
})
}
constructor(props){
super(props);
this.state = {
datatable: {
columns: [
{
label: 'CIF',
field: 'cif',
width: 150,
attributes: {
'aria-controls': 'DataTable',
'aria-label': 'Name',
},
},
{
label: 'Data creare',
field: 'data_creare',
width: 270,
},
{
label: 'ID Solicitare',
field: 'id_solicitare',
width: 200,
},
{
label: 'Tip',
field: 'tip',
sort: 'asc',
width: 100,
},
{
label: 'ID',
field: 'id',
sort: 'disabled',
width: 150,
},
{
label: 'Detalii',
field: 'detalii',
sort: 'disabled',
width: 100,
},
],
rows: [
],
}
}
}
render() {
return(
<div>
<MDBDataTableV5 hover entriesOptions={[5, 20, 25]} entries={5} pagesAmount={4} data=
{this.state.datatable} fullPagination />
</div>
);
}
}
export default ListaMesaje;
You should do simply replace你应该做简单的替换
for(var i = 0; i < 3; i++) {
this.setState({datatable:{...this.state.datatable,rows:persons.mesaje[i]}})
}
to到
this.setState({datatable:{...this.state.datatable,rows:[...persons.mesaje]}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.