我正在尝试从 jsonplaceholder
获取数据通过axios
并迭代该数据并将该数据放入reactstrap表中。我收到错误:Expected an assignment or function call and instead saw an expression
。我不完全确定我在这里做错了什么。任何帮助是极大的赞赏。
这是我的代码:
render() {
const data = axios.get("https://jsonplaceholder.typicode.com/todos")
.then(response =>
this.data = response.data,
this.data.forEach((item) => {
<tr>
<td>{item.userId}</td>
<td>{item.id}</td>
<td>{item.title}</td>
<td>{item.completed}</td>
</tr>
})
)
return (
<div className="App">
<header className="App-header">
<Table>
<thead>
<tr>
<th>
User ID
</th>
<th>
ID
</th>
<th>
Title
</th>
<th>
Completed
</th>
</tr>
</thead>
<tbody>
{
data
}
</tbody>
</Table>
</header>
</div>
);
}
}
错误是我尝试创建表行<tr>
的地方我的标签data
变量。
最佳答案
您应该使用生命周期方法从 API 加载数据并将其存储在状态中,并在状态更新时呈现它们。
试试这个
import React, { Component } from 'react';
import axios from 'axios';
class Example extends Component {
constructor(props) {
super(props);
this.state = {
todos: []
}
}
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/todos")
.then(response => {
this.setState({
todos: this.data
});
})
}
render() {
const { todos = [] } = this.state;
return (
<div className="App">
<header className="App-header">
<Table>
<thead>
<tr>
<th>User ID</th>
<th>ID</th>
<th>Title</th>
<th>Completed</th>
</tr>
</thead>
<tbody>
{todos.length ?
todos.map(todo => (
<tr>
<td>{todo.userId}</td>
<td>{todo.id}</td>
<td>{todo.title}</td>
<td>{todo.completed}</td>
</tr>
))
:
(<tr>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>)
}
</tbody>
</Table>
</header>
</div>
);
}
}
export default Example;
关于reactjs - 使用 Axios 获取 Json 并迭代 ReactStrap Table 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53905460/