gpt4 book ai didi

javascript - 在 React 中,如何在 HTML 表格中显示来自 API 的数据?

转载 作者:行者123 更新时间:2023-11-29 19:09:33 24 4
gpt4 key购买 nike

我正在尝试显示来 self 的示例 API 的数据。目前我可以遍历数组并显示所有标题,例如:

EventTitle1
EventTitle2
EventTitle3
...

这是我的代码:

class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
}

componentDidMount() {
var th = this;
this.serverRequest = axios.get(this.props.source)
.then(function(event) {
th.setState({
data: event.data
});
})
}

componentWillUnmount() {
this.serverRequest.abort();
}

render() {
var titles = []
this.state.data.forEach(item => {
titles.push(<h3 className=”events”>{item.title[0].value}</h3> );
})
return (
<div className=”container”>
<div className=”row”>
<div className=”col-md-6 col-md-offset-5">
<h1 className=”title”>All Events</h1>
{titles}
</div>
</div>
</div>
);
}
}

ReactDOM.render(
<App source=”http://localhost:8888/example/api/events" />,
document.getElementById(‘container’)
);

我如何创建一个 HTML 表格,以在表格中仅显示来自 API 的五个最新事件标题(以及后来的其他数据)?

例如:

return (
<table>
<tr>
<th>Event title</th>
<th>Event location</th>
</tr>
<tr>
<td>First event title {titles[0]} ?? </td>
<td>San Fran</td>
</tr>
<tr>
<td>Second event title {titles[1]} ??</td>
<td>London</td>
</tr>
</table>
);

最佳答案

创建 <tr> 的数组并将其添加到表中。

class App extends React.Component {
constructor() {
super();
this.state = {
data: []
}
}

componentDidMount() {
var th = this;
this.serverRequest = axios.get(this.props.source)
.then(function(event) {
th.setState({
data: event.data
});
})
}

componentWillUnmount() {
this.serverRequest.abort();
}

render() {
const contents = this.state.data.forEach(item => {
// change the title and location key based on your API
return <tr>
<td>{item.title}</td>
<td>{item.location}</td>
</tr>
})
return (
<div className="container">
<div className="row">
<div className="col-md-6 col-md-offset-5">
<h1 className="title">All Events</h1>
<table>
<tr>
<th>Event title</th>
<th>Event location</th>
</tr>
{contents}
</table>
</div>
</div>
</div>
);
}
}

ReactDOM.render(
<App source="http://localhost:8888/example/api/events" />,
document.getElementById("container")
);

关于javascript - 在 React 中,如何在 HTML 表格中显示来自 API 的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234757/

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