在我的代码中,我告诉 API 从 componentDidMount()
内的端点检索数据。
componentDidMount() {
this.setState({
lessons: API.getAllLessons()
})
}
然后我将列表中的每个项目映射到渲染中的单个面板
render() {
return (
this.state.lessons.map((lesson)=>{
<LessonItem lesson={lesson}/>
})
);
}
但是,当映射时,它会抛出错误,因为它尝试映射的状态下的属性为 null,但不应如此,因为数据是从 API 返回的。
Uncaught (in promise) TypeError: Cannot read property 'lessons' of null
我的状态是这样定义的
export interface AuthenticatedHomeState {
currentUser: any;
lessons: any;
}
最佳答案
您可能没有初始化状态。
constructor(props){
super(props)
this.state = {
lessons: [] //default value
}
}
componentDidMount() {
this.setState({
lessons: API.getAllLessons()
})
}
但是,如果 API.getAllLessons 返回 Promise,您将需要以不同的方式处理它。
关于javascript - Reactjs,无法读取 null 的属性 'lessons',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50028801/