gpt4 book ai didi

javascript - React.js 从数组创建多个表

转载 作者:行者123 更新时间:2023-11-30 14:53:54 24 4
gpt4 key购买 nike

我已经为我的问题寻找了解决方案,但没有任何效果可能是因为我缺乏理解。

我正在尝试使用 React.js 创建动态长度的表格。

我使用 axios 在我的项目中调用 API返回 JSON 对象数组的库,我们不知道返回数组的大小,但对于数组中的每个 JSON 对象,我需要创建一个表并添加其数据。以下是 API 调用返回的示例。

[

{
"feedbackID": 12,
"posterID": "John",
"comment": "shortcomment"
},
{
"feedbackID": 23,
"posterID": "billy",
"comment": "long comment"
}
]

因此对于这个返回,我将不得不创建 2 个表,一个在另一个下面,如下所示:

| Feedback ID | 12           |
| Poster ID | John |
| Comment | shortcomment |

| Feedback ID | 23 |
| Poster ID | billy |
| Comment | long comment |

到目前为止,这是我的代码:

   export class ViewFeedback extends Component {
constructor(props) {
super(props)
this.state = {
feedback: []
}
}

componentDidMount() {
var id = this.props.match.params.id;

// this returns the JSON array like shown above
getfeedback(id).then((response) => {


this.setState({feedback:response})

})


}

我完全不知道如何制作表格,我尝试了 createElementGrid 但我做错了,甚至无法编译代码.

最佳答案

这应该有效:

renderTable = () => {
return this.state.feedback.map(value => {
return (
<table>
<tr>
<td>Feedback ID</td>
<td>{value.feedbackID}</td>
</tr>
<tr>
<td>Poster ID</td>
<td>{value.posterID}</td>
</tr>
<tr>
<td>Comment</td>
<td>{value.comment}</td>
</tr>
</table>
)
})
}

render () {
return <div>{this.renderTable()}</div>;
}

Render 方法主要是一个 View ,因此鼓励将逻辑移动到一个单独的方法。

关于javascript - React.js 从数组创建多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47673226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com