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

无法访问json对象的值?无法读取未定义的属性“company_about”?,json,reactjs,typescript,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,

这是我的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.logdetails[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.logdetails[0].company\u profile返回未定义的??? 它给出的错误是:

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


有人能帮忙吗???

您的获取代码是异步的,您没有为此设置默认值。您可以尝试几个不同的选项。您可以重新定义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。请在渲染中使用条件语句,以便在请求未完成且您的状态没有详细信息时,不会加载任何内容

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

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

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

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

查看在尝试访问某些复杂对象时是否已填充状态。e、 g.在第一次渲染期间,this.state.details可能未定义,因此此错误。是的,在第一次渲染期间,它未定义?但后来它被定义了??我仍然收到了这个错误。还将一些有意义的字符串添加到console.logs中,并查看它的呈现方式。我尝试了JSON.stringify,但仍然没有定义:为了OP的好处,您应该在这里添加一个代码示例。是的,没错-正在工作:我刚刚检查了ifdetails[0]!==未定义{console.logdetails[0].company\u about}然后它给了我结果:示例是:检查详细信息是否真实,然后检查详细信息[0],然后返回详细信息[0]。company\u配置文件可以表示为详细信息和详细信息[0]&&details[0]。company\u about。非常感谢朋友,你为我多省了几杯咖啡:添加了一些示例代码,以显示我如何加载父容器数据,然后将其传递给子容器。1。此代码是否会在每次呈现期间公开呈现{this.getJobDetails.thenresponse=>{console.logresponse[0]}}?2.React知道如何在render中处理承诺吗?render与任何其他函数一样,只要返回React元素或null,就可以在其中执行任何javascript。每次渲染时,它都会响应请求,因此它可能不是最有效的。您可以提供一个默认状态,或者一个条件渲染,比如加载。我会编辑我的帖子。