所以我正在关注一些关于如何在 react 中获取 api 的教程,并且我正在使用 async 来执行此操作,但是我收到以下错误,即 0 的属性未定义
未处理的拒绝(TypeError):无法读取未定义的属性“0”
下面是我的代码,让我知道我哪里出错了
import React from 'react';
import './App.css';
class GetStudents extends React.Component {
state = {
loading:true,
student:null
}
async componentDidMount() {
const url = "http://localhost:3200/students";
const response = await fetch(url);
const data = await response.json();
this.setState({student:data.results[0], loading:false});
}
render() {
if (this.state.loading) {
return <div>loading ...</div>
}
if (this.state.student) {
return <div>No student was found ...</div>
}
return(
<div>
<div>{this.state.student._id}</div>
<div>{this.state.student.role_num}</div>
<div>{this.state.student.first_name}</div>
<div>{this.state.student.last_name}</div>
<div>{this.state.student.marks}</div>
</div>
)
}
}
export default GetStudents;
好的,所以我该错误不再存在,但知道我有此错误无法读取未定义的属性“_id”,这是我尝试从http://localhost:3200/students调用的 url