未捕获(在承诺中)TypeError:无法读取未定义的属性(读取“map”)
2022-03-12
1170
我现在在我的 React Web 应用上遇到了这个问题。我尝试从我创建的 Laravel API 映射学生数据。突然,Web 应用向我显示此错误
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'map')
以下是我的代码
state = {
students: [],
loading: true,
}
async componentDidMount() {
const res = await axios.get('http://localhost:8000/api/students');
/* console.log(res); */
if(res.data.status === 200){
this.setState({
students: res.data.students,
loading: false,
});
}
}
render(){
var student_HTMLTABLE = "";
if(this.state.loading){
student_HTMLTABLE =
<tr>
<td colSpan="7">
<h2>Loaidng ...</h2>
</td>
</tr>
}
else{
student_HTMLTABLE =
this.state.students.map( (item) => {
return(
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.course}</td>
<td>{item.email}</td>
<td>{item.phone}</td>
<td><Link to={`/edit-students/${item.id}`} className="btn btn-warning btn-sm">Edit</Link></td>
<td><Link to={`/delete-students/${item.id}`} className="btn btn-danger">Delete</Link></td>
</tr>
);
});
}
请帮我解决这个问题,谷歌搜索了将近 1 个小时,但仍然卡住 :(
2个回答
This error is because your value is null and you're not checking null. Try this code
// null check
{
this.state.students && this.state.students.map((student , idx)=>{
// do some thing
})
}
zain ul din
2022-03-12
只需将其更改为
students: res.data.students ?? [],
如果学生或数据为空,这将解决您的问题。
Hayyaun
2022-03-12