Javascript Reactjs,无法读取属性';课程';空的
在我的代码中,我告诉API从Javascript Reactjs,无法读取属性';课程';空的,javascript,reactjs,Javascript,Reactjs,在我的代码中,我告诉API从componentDidMount()内的端点检索数据 然后,我将列表中的每个项目映射到渲染中的单个面板 render() { return ( this.state.lessons.map((lesson)=>{ <LessonItem lesson={lesson}/> }) ); } 你可能没有初始化这个州 constructor(props){ super(props) this
componentDidMount()
内的端点检索数据
然后,我将列表中的每个项目映射到渲染中的单个面板
render() {
return (
this.state.lessons.map((lesson)=>{
<LessonItem lesson={lesson}/>
})
);
}
你可能没有初始化这个州
constructor(props){
super(props)
this.state = {
lessons: [] //default value
}
}
componentDidMount() {
this.setState({
lessons: API.getAllLessons()
})
}
但是,如果API.getAllLessons返回一个承诺,您需要以不同的方式处理它。您可能没有初始化状态
constructor(props){
super(props)
this.state = {
lessons: [] //default value
}
}
componentDidMount() {
this.setState({
lessons: API.getAllLessons()
})
}
但是,如果API.getAllLessons返回一个承诺,您将需要以不同的方式处理它。您正在调用componentDidMount,这意味着它将在调用render后运行。您需要调用componentWillMount()您正在调用componentDidMount,这意味着它将在调用render后运行。您需要调用componentWillMount()您必须首先初始化状态,然后调用api,如果api调用是承诺调用(通常是),则必须以这种方式读取值
constructor(props){
super(props)
this.state = {
lessons: [] //set default value for lessons
}
}
componentDidMount() {
API.getAllLessons().then((resp)=>{
this.setState({
lessons: resp.data
})
})
}
您必须首先初始化状态,然后调用api,如果api调用是承诺调用(通常是),则必须以这种方式读取值
constructor(props){
super(props)
this.state = {
lessons: [] //set default value for lessons
}
}
componentDidMount() {
API.getAllLessons().then((resp)=>{
this.setState({
lessons: resp.data
})
})
}
getAllLessons
是否返回一个Promise
?我不确定如何确定,但我认为是的。this.state.lessons
在componentDidMount
之前是空的,所以在第一次渲染时,它是null
,除非设置默认值,如this.state={lessons:[]}
我不使用经典构造函数,我已经更新,以尝试和反映这一点。实现构造函数只会让它抱怨课程是只读的。完整组件代码确实返回了一个承诺,但我不确定如何确定,但我认为它确实返回了承诺。这个状态。课程在组件安装之前是空的,所以在第一次渲染时,它是空的,除非设置默认值,如this.state={lessons:[]}
我不使用经典构造函数,否则我已更新以尝试反映这一点。实现一个构造器只会让它抱怨课程是只读的,完全是组件代码。是的,这家伙说的。我通常会这么做,但我正在做的项目却完全不同。我已经更新了帖子,向你展示了我的状态是如何处理的。一旦我实现了构造器,它就会抱怨课程是只读的。是的,这家伙说的。我通常会这样做,但我正在做的项目却完全不同。我已经更新了帖子,向您展示了我的状态是如何处理的。一旦我实现了构造函数,它就会抱怨课程是只读的