json - React Router 从 API 获取数据
问题描述
我是新手,现在正在开发一个必须从 API 获取一些数据的应用程序。
我的组件应该获取数据并返回一个 Json 对象并填充一个表。
class RenderTable() extends React.Component {
render() {
fetch("http://localhost:6002/api?act=getall")
.then(data=> data.json())
.then(
result => {
this.setState({
library: result
});
console.log(this.state.result);
},
error => {
this.setState({
library: "error"
});
return null;
}
);
}
render() {
return (
<div id="libTable">
<table>
<tbody>
<tr>
<th>Genre</th>
<th>Description</th>
<th>Date</th>
<th>Price</th>
</tr>
<tr>
<td>{JSON.stringify(this.state.library)}</td>
</tr>
</tbody>
</table>
</div>
);
} }
<Route path="/RenderTable" component={RenderTable} />
我的库是一个数组,我在我的主应用程序容器中初始化为一个空数组。路由路径在我的主应用程序中的渲染下。任何帮助深表感谢。
解决方案
在 render 方法中映射您的状态,如下所示:
return (
<div id="libTable">
<table>
<tbody>
<tr>
<th>Genre</th>
<th>Description</th>
<th>Date</th>
<th>Price</th>
</tr>
{this.state.library.map(book => (
<tr>
<td>{book.genre}</td>
<td>{book.description}</td>
<td>{book.date}</td>
<td>{book.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
您的类组件中还有一些其他奇怪的错误,例如 2 个渲染方法。一个可能的正确实现如下所示:
class RenderTable extends React.Component {
state = {
library: [],
error: ""
};
componentDidMount() {
fetch("http://localhost:6002/api?act=getall")
.then(data => data.json())
.then(result => {
this.setState({
library: result
});
console.log(this.state.result);
})
.catch(error =>
this.setState({
error
})
);
}
render() {
return (
<div id="libTable">
<table>
<tbody>
<tr>
<th>Genre</th>
<th>Description</th>
<th>Date</th>
<th>Price</th>
</tr>
{this.state.library.map(book => (
<tr>
<td>{book.genre}</td>
<td>{book.description}</td>
<td>{book.date}</td>
<td>{book.price}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
推荐阅读
- html - 侧边栏的背景不会随着滚动而延伸到底部
- heroku - Heroku 爱好测功机和免费数据库?
- python - 在基于时间序列数据的相关对图中显示更多时间细节
- numbers - 从右到左修剪 Wolfram 中的数字
- delphi - Delphi XE7 - 将备忘录转换为 UTF8
- directx - DirectX 数学库是否具有从四元数获取欧拉角的功能?
- haskell - mapA 用于可能阻塞的流处理器(异步电路)
- jmeter - 即使 UI 不符合预期,脚本是否会在 JMeter 中运行?
- mysql - 我的代码在这里有什么不正确的地方?我不明白它有什么问题?
- angular - 如何正确处理httpClient?