【发布时间】:2021-11-23 14:41:20
【问题描述】:
import React,{Component} from 'react'
class Todo extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
fetchdata: [],
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/todos")
.then((res) => res.json())
.then((json) => {
this.setState({
data: json,
});
});
}
componentDidUpdate(){
this.fetchdata();
}
fetchdata=()=>{
fetch("https://jsonplaceholder.typicode.com/users/:id")
.then((res) => res.json())
.then((json) => {
this.setState({
fetchdata: json.data,
});
});
}
render() {
const { data, fetchdata } = this.state;
return (
<div>
<div className="Todos row g-3">
<table class="table col-auto">
<thead>
<tr>
<th scope="col">Todo</th>
<th scope="col">Title</th>
<th scope="col">Status</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
{this.state.data.map((data, index) => (
<tr key={index}>
<th scope="row">{data.id}</th>
<td>{data.title}</td>
<td>{data.completed}</td>
<td>
<button onClick={this.fetchdata.bind(this, data)}>
View
</button>
</td>
</tr>
))}
;
</tbody>
</table>
</div>
<div className="show-data col-auto">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Todo_Id</th>
<th scope="col">Todo_title</th>
<th scope="col">User_id</th>
</tr>
</thead>
<tbody>
{this.state.fetchdata.map((fetchdata, index) => (
<tr key={index}>
<th scope="row">{fetchdata.id}</th>
<td>{fetchdata.name}</td>
<td>{fetchdata.email}</td>
</tr>
))}
;
</tbody>
</table>
</div>
</div>
);
}
}
export default Todo
这是我的代码,我想在单击按钮时加载数据,但出现错误:“无法读取未定义的属性(读取 'map')”。我是反应js的新手,不知道该怎么做。数据未按 id 点击按钮加载到下表中。第一个表数据加载正确。
【问题讨论】:
标签: javascript reactjs react-native api fetch-api