我是新来的反应者,现在正在开发一个必须从API提取一些数据的应用程序。
我有应该获取数据并获取Json对象并填充表的组件。
enter code here
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>
);
}}
enter code here
<Route path="/RenderTable" component={RenderTable} />
我的库是一个数组,我在主应用程序容器中将其初始化为空数组。路由路径在我的主应用程序的render下。非常感谢您的帮助。
像这样在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);
},
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>
);
}
}
您需要像这样感染componentDidMount中的数据:
import React from "react";
class RenderTable extends React.Component {
componentDidMount() {
fetch("http://localhost:6002/api?act=getall")
.then(data => data.json())
.then(result => {
this.setState({
library: result
});
console.log(this.state.result);
})
.catch(err => {
console.log(err);
this.setState({ error: err.message });
});
}
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>
);
}
}
export default RenderTable;
看来您有两个渲染功能。除非自从我上次更新React以来有什么改变,否则它将无法正常工作。无论如何,您不应该在render函数中设置状态,这纯粹是为了渲染控件。
相反,将fetch调用添加到componentWillMount
class RenderTable() extends React.Component {
componentWillMount() {
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>
);
}
}