首页 > 解决方案 > 无法访问 json 对象的值?无法读取未定义的属性“company_about”?

问题描述

这是我的 JSON

[
{
    "id": 1,
    "job_id": 1,
    "company_profile": "Sales and Marketing",
    "company_about": "Established in 1992 , it is a renouned marketing company",
    "company_product": "Ford,Mustang,Beetle",
    "key_skills": "commmunication,english,spanish,german",
    "qualification": "High School,Masters",
    "job_description": "Must be a Local of Mumbai",
    "created_at": null,
    "updated_at": null
}

]

我试图获得它的价值。这是我记录它们的反应代码。

 public getJobDetails = (jobid: number) => {
const JobId = jobid;
fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
  .then(response => response.json())
  .then(
    responseJson => {
      console.log(responseJson);
      this.setState({ details: responseJson });
    },
    () => {
      console.log(this.state.details);
    }
  )
  .catch(error => {
    console.error(error);
  });


 }

      public render() {
        const { details } = this.state;
        console.log(details);
        console.log(details[0]);

console.log(details[0]) 返回

{id: 1, job_id: 1, company_profile: "Sales and Marketing", company_about: "Established in 1992 , it is a renouned marketing company", company_product: "Ford,Mustang,Beetle", …}

但是为什么 console.log(details[0].company_profile) 返回 undefined ???它给出的错误是:

TypeError:无法读取未定义的属性“company_about”

谁能帮忙??

标签: jsonreactjstypescript

解决方案


在渲染中使用条件语句,这样如果您的请求未完成并且您的状态没有详细信息但它不会加载任何内容。

编辑---示例代码(不是您的应用程序,而是我的意思的概念)

从'react'导入反应,{组件,片段};

export class App extends Component {
  constructor(){
    super()
    this.state = { 
      data: [],
      isLoading: true
     }
  }

  componentWillMount(){
    this.fetchDetails()
  }

   fetchDetails = () =>{
     fetch('/some/url')
     .then(res => res.json())
     .then( => {
       this.setState({data, isLoading: false})
     })
   }


  render() { 
    return ( 
      <Fragment>
        {!this.state.isLoading && <ChildComponent data={this.state.data}} />}
      </Fragment>
     );
  }
}

推荐阅读