当反应状态是数组时,无法读取未定义的属性“目标”

时间:2019-01-09 06:17:45

标签: arrays reactjs state

当我的反应状态是一个对象时,我可以在render方法中获取它的属性, 但是当我将状态设置为array并在render方法中使用state [0] .property时,它给了我未定义的错误,无法弄清楚,有什么帮助吗???谢谢!!!

class App extends Component {
 state={
  dataArray:[]
 }
  componentDidMount(){
     this.getTrainInfo();
   }

getTrainInfo=()=>{

  fetch('https://api-v3.mbta.com/routes')
      .then(response=>response.json())
      .then(res=>{ 
          //res will return an array of objects
          let arr=[];
          let data={};
         data.destination=res.data[0].attributes.direction_destinations[0];
          data.lineID=res.data[0].relationships.line.data.id

          arr.push(data);

          this.setState({dataArray:arr});
         //I put a console.log(dataArray) here, I can get 
         //  [{destination:xxx, lineID:xxx }] back.
      })


  }
   render() {
     //in here, I also can get the array: [{destination: xxx, lineID: xxx}]
    let data=this.state.dataArray;  
      //but in here, I get error saying property destination is undefined, 
     //why?
    let destination=data[0].destination;
     //console.log(destination);
   return (
    <div className="App">
      <h1>Train info</h1>
    </div>
   );
   }
  }

2 个答案:

答案 0 :(得分:0)

这是正常现象。在执行componentDidMount()中的逻辑之前,React将为您提供一次组件。这就是为什么会收到未定义错误的原因,因为初始状态从一个空数组开始。

要解决此问题,通常的做法是在组件使用新数据更新时具有“加载状态”。因此,当状态最终更新时,您的组件将重新呈现并显示所需的内容。

在渲染中,尝试执行以下操作:

   render() {
    let data=this.state.dataArray;
    if(this.state.dataArray.length == 0){
       return Loading...
    } else {
        return (
          <div className="App">
            // whatever logic you want to display
            <h1>Train info</h1>
          </div>
    )
   }

答案 1 :(得分:0)

您需要添加条件,因为在初始渲染时,dataArray为空数组,并且其中没有任何对象。

从第二个病房开始,您在dataArray中有数据,因此请添加以下条件

    if(this.state.dataArray.length){ //this condition will be true when dataArray length is greater than zero
         let destination=data[0].destination;
         console.log(destination); //this will print the value
     }
相关问题