我从post请求中填写了我的myArray。我想用这些值动态填充表,但它不会呈现任何内容。
class Reports extends React.Component {
constructor(props) {
super(props);
this.state = {
id:"",
myArray: [],
}
}
componentDidMount(e) {
console.log("fetching")
fetch('/getMetaReport', {
method: 'post',
headers: {'Content-Type':'application/json', 'Accept': 'application/json'},
body: JSON.stringify({id: 7}),
}).then(res => res.json()).catch(error => {
console.error('Error:', error);
})
.then(response => {
console.log(response);
this.state.myArray.push(response);
console.log(this.state.myArray)
})
}
我可以在控制台中打印值,但是我不能用它们填充表。
return (
<div className={s.root}>
<h2 className="page-title" style={{color: "black"}}>
Reports
</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Date</th>
</tr>
</thead>
<tbody>
{
this.state.myArray.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.date}</td>
<td/>
</tr>
))
}
</tbody>
</table>
</div>
)
}
为什么它什么都不呈现,我如何用JSON数组中的值动态填充我的表?提前谢谢你。
发布于 2021-04-23 06:38:42
你不是在触发重现。尝尝这个
this.setState({'myArray': [...this.state.myArray, response]})
发布于 2021-04-23 06:58:25
虽然Cody E提到的内容是正确的,但如果您想将新项‘推入’到现有数组中(而不是替换整个数组),最好的方法是使用prevState参数。否则你可能会发现副作用。
this.setState((prevState) => {
return { myArray: [...prevState.myArray, ...response] }
})
https://stackoverflow.com/questions/67221613
复制相似问题