【问题标题】:Cannot access value of a json object ? Cannot read property 'company_about' of undefined ?无法访问 json 对象的值?无法读取未定义的属性“company_about”?
【发布时间】:2019-05-21 09:34:18
【问题描述】:

这是我的 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”

谁能帮忙??

【问题讨论】:

  • 当你试图访问一些复杂的对象时,看看是否已经填充了状态。例如在第一次render this.state.details 可能是undefined,因此出现此错误。
  • 是的,在第一次渲染期间它是未定义的?但后来它变得定义?我仍然收到此错误。
  • 也添加一些有意义的字符串到你的console.logs,看看它是如何呈现的。
  • 我试过 JSON.stringify ,但仍然未定义:(

标签: json reactjs typescript


【解决方案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>
     );
  }
}

【讨论】:

  • 您应该在此处添加一个代码示例以使 OP 受益。
  • 是的,伙计,现在正在工作:) 我刚刚检查了 if(details[0] !== undefined){ console.log(details[0].company_about) } 然后它给了我结果:)
  • 例如:检查details是否真实,然后检查details[0],然后返回details[0].company_profile可以表示为details &amp;&amp; details[0] &amp;&amp; details[0].company_about
  • 非常感谢朋友,你为我节省了一天的咖啡:)
  • 添加了一些示例代码来展示我如何加载父容器数据,然后将其传递给子容器。
【解决方案2】:

您的获取代码是异步的,并且您没有为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

【讨论】:

  • 1.这段代码public render() { this.getJobDetails().then(response =&gt; {console.log(response[0])}) } 会在每次渲染期间运行吗? 2. React 是否知道如何处理 render 内部的 promise?
  • Render 就像任何其他函数一样,您可以在其中执行任何您想要的 javascript,只要您返回一个 react 元素或 null。它将请求每次渲染,因此它可能不是最有效的。您可以提供默认状态,或者像加载这样的条件渲染。我会编辑我的帖子。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 2023-03-20
    • 2021-11-18
    • 1970-01-01
    • 2021-11-02
    • 2019-11-13
    • 2023-04-01
    • 2015-01-10
    • 2021-04-30
    相关资源
    最近更新 更多