【问题标题】:Unhandled Rejection (TypeError): Cannot read property '0' of undefined未处理的拒绝(TypeError):无法读取未定义的属性“0”
【发布时间】:2019-11-13 21:06:27
【问题描述】:

所以我正在关注一些关于如何在 react 中获取 api 的教程,并且我正在使用 async 来执行此操作,但是我收到以下错误,即 0 的属性未定义

未处理的拒绝(TypeError):无法读取未定义的属性“0”

下面是我的代码,让我知道哪里出错了

import React from 'react';
import './App.css';

class GetStudents extends React.Component {
state = {
  loading:true,
  student:null
}

async componentDidMount() {
  const url = "http://localhost:3200/students";
  const response = await fetch(url);
  const data = await response.json();
  this.setState({student:data.results[0], loading:false});


}
render() {
  if (this.state.loading) {
    return <div>loading ...</div>
  }

  if (this.state.student) {
    return <div>No student was found ...</div>
  }
   return(
     <div>
         <div>{this.state.student._id}</div>
         <div>{this.state.student.role_num}</div>
         <div>{this.state.student.first_name}</div>
         <div>{this.state.student.last_name}</div>
         <div>{this.state.student.marks}</div>
     </div>
   )


}

}
export default GetStudents;

好的,所以我不再存在那个错误,但知道我有这个错误 无法读取未定义的属性“_id” 这是我试图从http://localhost:3200/students调用的网址

【问题讨论】:

  • 解析的 JSON 可能没有 results 属性,因此尝试访问 0 会导致您的错误。您可以登录 data 以查看其结构。
  • 请在此处分享 response.json() 数据
  • @AddWebSolutionPvtLtd const data = await response.json(); this.setState({student:data.results[0], loading:false});这是你想要的吗
  • 不,我想看看你的 console.log(data)。
  • @AddWebSolutionPvtLtd 在我的 console.log(data) 中没有任何显示;

标签: reactjs


【解决方案1】:

试试this

async componentDidMount() {
  const url = "http://localhost:3200/students";
  await fetch(url)
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(JSON.stringify(myJson));
    //First check what type of data you are getting here and then try to set your state as below.
    //this.setState({student:data.results[0], loading:false});
  })
  .catch(error => console.error(error)); //If error occurs you will get here
}

更新

在上面的获取函数中设置状态,您使用console.log您的数据,

this.setState({student:myJson, loading:false});

然后在渲染函数中你可以迭代你的状态变量,

render() {
  if (this.state.loading) {
    return <div>loading ...</div>
  }

  if (this.state.student===null) {
     return <div>No student was found ...</div>
  }
  return(
     <div>
     {
      this.state.student.map((student)=>{
       return <> //React Fragment short syntax.
        <div>{student._id}</div>
        <div>{student.role_num}</div>
        <div>{student.first_name}</div>
        <div>{student.last_name}</div>
        <div>{student.marks}</div>
        </>
     })
    }
   </div>
  )
}

【讨论】:

  • @ravbagul91 好的,所以我在控制台中得到了结果,现在我想在网页上显示它
  • 你得到的是什么数组或对象?在此处粘贴您的 console.log。
  • [{"_id":"5d0381ad681a2a3aa1dc5873","role_num":"20","first_name":"M","last_name":"P","marks":null},{ "_id":"5d10b6124adac42c4467cb88","role_num":6,"first_name":"ff","last_name":"Khan","marks":91},{"_id":"5d10b65f4adac42c4467cb89","role_num": 6,"first_name":"Mohammed","last_name":"Khan","marks":91},{"_id":"5d11b586d76c463d30d02355","role_num":"97","first_name":"Mazz", "last_name":"Ahadas","marks":null}]
  • 这就是我得到的
  • 我做了更改,现在我得到了这个解析错误:相邻的 JSX 元素必须被包裹在一个封闭的标签中
【解决方案2】:

请用try{...} catch{} 块包围你的代码,这样如果发生不好的事情你可以看到错误。我认为你的 if 是错误的,所以我修复它

import React from 'react';
import './App.css';

class GetStudents extends React.Component {
state = {
  loading:true,
  student:null
}

async componentDidMount() {
 try{
  const url = "http://localhost:3200/students";
  const response = await fetch(url);
  const data = await response.json();
  this.setState({student:data.results[0], loading:false});
}
 catch(err){
  console.log(err)
}

}
render() {
  if (this.state.loading) {
    return <div>loading ...</div>
  }

  if (!this.state.student) { 
    return <div>No student was found ...</div>
  }
   return(
     <div>
         <div>{this.state.student._id}</div>
         <div>{this.state.student.role_num}</div>
         <div>{this.state.student.first_name}</div>
         <div>{this.state.student.last_name}</div>
         <div>{this.state.student.marks}</div>
     </div>
   )


}

}
export default GetStudents;

给你写

if (this.state.student) { 
    return <div>No student was found ...</div>
 }

而且你将 student 设置为 null,所以我们必须将其更改为:

if (!this.state.student) { 
    return <div>No student was found ...</div>
 }

【讨论】:

  • 我在我的控制台中得到这个 TypeError: Cannot read property '0' of undefined at GetStudents.componentDidMount (getstudents.js:15)
  • @Arnald 你能用 Postman 之类的东西来测试你的服务器,或者用你的服务器代码更新你发布的内容吗?可能是你的服务器问题。
猜你喜欢
  • 2019-04-07
  • 2021-05-01
  • 2019-07-19
  • 2019-06-03
  • 2020-04-09
  • 2021-10-19
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多