设置后未定义reactjs状态数组属性

时间:2019-04-29 15:32:26

标签: reactjs

我正在努力理解为什么在设置状态并正确显示所有内容后为什么无法访问sections状态数组元素。当我通过控制台记录部分状态数组的[0]元素时,发生错误。我也在下面粘贴了控制台日志输出。

// Load the course template 
  this.props.firebase
  .course(authUser.courseId)
  .get()
  .then((course) => {
    if (course.exists) {
      console.log("Course data:", course.data());
      this.setState({shortCode: course.data().shortCode});
      this.setState({title: course.data().title},()=>{
        let activities = [];
        course.data().sections.map(sect=>{
          this.props.firebase.getDocByIdFrom("courseActivities",sect.id)
          .get()
          .then((activity)=>{
            activities.push(activity.data()); 
          })
          .catch(error => {
            console.log(error);
          });
        });  
        this.setState({sections:activities},()=>{
          console.log("SECTIONS ",this.state.sections);
          console.log("SECTION 0 "+this.state.sections[0].title);
        });  
      });
    } else {
        // doc.data() will be undefined in this case
        console.log("No such course!");
    }
  })
  .catch(error => {
    console.log(error);
  });

https://drive.google.com/open?id=15WZM20Z0qlgHotjiRR4l5uWYDGl260Lh

1 个答案:

答案 0 :(得分:0)

类似以下内容将确保在将actitivies加载到状态之前,所有.get()操作都已发生:

let activities = [];
Promise.all(course.data().sections.map(sect => {
  return this.props.firebase.getDocByIdFrom("courseActivities", sect.id)
    .get()
    .then(activity => activities.push(activity.data()))
  }))
.then(() => {
  this.setState({ sections:activities }, ()=>{
    console.log("SECTIONS ",this.state.sections);
    console.log("SECTION 0 "+this.state.sections[0].title);
  }); 
});