无法访问json对象的值?无法读取未定义的属性“ company_about”?

时间:2018-12-20 20:51:41

标签: json reactjs typescript

这是我的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)返回未定义??? 它给出的错误是:

  

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

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

在渲染器中使用条件语句,以便如果您的请求未完成并且您的州没有详细信息,则它不会加载任何内容。

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

从'react'导入React,{Component,Fragment};

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>
     );
  }
}

答案 1 :(得分:0)

您的获取代码是异步的,并且没有为this.state设置默认值。您可以尝试几个不同的选项。您可以重新定义getJobDetails以返回承诺而不是更改状态:

class MyComponent extends React.Component {

     public getJobDetails = (jobid: number) => {
        const JobId = jobid;
        return fetch('http://127.0.0.1:8000/api/jobs/detail/' + JobId)
     }

     public render() {
         this.getJobDetails().then(response => {console.log(response[0])})
     }
}

或者您可以设置默认状态

class MyComponent extends React.Component {
    public state = {
        details: [...]
    }
}

编辑

在每个渲染周期执行网络请求不是很有效,因此它可能不是最佳途径。我也忘记了第三种选择,像这样的条件渲染:

class MyComponent extends React.Component {
    state = { loading: true }
    getJobDetails = (jobid: number) => {
        fetch(...).then((response) => {
            this.setState({details: response})
            this.setState({loading : false})
        })
    } 
    render() {
        return this.state.loading ? <h1>Loading...</h1> : <div>{this.state.deatils}</div>
    }
}

如果您想将其作为对象访问,则不应将数据转换为JSON

答案 2 :(得分:0)

尝试更多日志记录,例如:

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(`Fetch resulted in ${JSON.stringify(responseJson)}`);
      this.setState({ details: responseJson });
    },
    () => {
      // This line is supposed to act as error handler, but there is no error handling
// See this - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Syntax

      console.log(this.state.details);
    }
  )
  .catch(error => {
    console.error(`Fetch resulted in error ${JSON.stringify(error)}`);
  });


 }

      public render() {
        const { details } = this.state;
        console.log('Rendering...'); 
        console.log(`step 1. ${JSON.stringify(details)}`);
// let's see if details are not undefined and try next level
        details && console.log(`step 2. ${JSON.stringify(details[0])}`);
相关问题