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

时间:2019-07-03 08:08:55

标签: reactjs

所以我正在关注一些有关如何在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调用的网址

2 个答案:

答案 0 :(得分:0)

请用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>
 }

答案 1 :(得分:0)

尝试this

// load the models
$this->loadModel('Questionnaire');
$this->loadModel('Questions');
// get the questions to questionnaire association - will need the PK name
$qAssoc = $this->{'Questions'}->associations()->get('Questionnaire');
// get the existing entity to copy
$existingEntity = $this->{'Questionnaire'}->get($id, [
    'contain' => ['Questions'],
]);
// clean up the existing entity
$existingEntity->unsetProperty($this->{'Questionnaire'}->getPrimaryKey());
$existingEntity->unsetProperty('created');
$existingEntity->unsetProperty('modified');
// clean up the associated records of the existing entity
foreach ($existingEntity->questions as &$q) {
    $q->unsetProperty($this->{'Questions'}->getPrimaryKey());
    $q->unsetProperty($qAssoc->getForeignKey());
}
// create a new entity and patch it with source data
$newEntity = $this->{'Questionnaire'}->patchEntity(
        $this->{'Questionnaire'}->newEntity(),
        $existingEntity->toArray()
);
// save the new entity
$result = $this->{'Questionnaire'}->save($existingEntity);

更新

在上述提取功能中设置状态,您可以使用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

然后在render函数中,您可以迭代状态变量,

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