【问题标题】:Cannot read property of data null in ReactJs when fetching from JSON从 JSON 获取时无法读取 ReactJs 中数据 null 的属性
【发布时间】:2020-01-16 08:05:38
【问题描述】:

我是新手,尝试在 React JS 中获取 JSON 数据,但收到此错误:

TypeError: Cannot read property 'data' of null

我的代码是:

import React from 'react';

export default class FetchJson extends React.Component {

    componentDidMount()
    {
        fetch('https://api.myjson.com/bins/9i63i')
        .then((response) => response.json())
        .then((findresponse) =>{
            this.setState({ data: findresponse })
            //console.log(this.state.data);
            //console.log(findresponse.DesignName);

        })
    }

    render() {
        return(
            <ul>
                {this.state.data.map((x,i) => <li key={i}>{x.DesignName}</li>)}
            </ul>
        );
    }
}

你可以在这里看到json数据:http://myjson.com/9i63i 我想检索键DesignName 的值,即part1,这没有发生。 请参阅注释行:两者都给了我价值。但是当我尝试在渲染内的返回方法中访问它时。我收到错误:TypeError: Cannot read property 'data' of null 在这一行:

{this.state.data.map((x,i) => <li key={i}>{x.DesignName}</li>)}

如何解决?

【问题讨论】:

  • 可能是因为 render() 在你之前运行 .then() 回调已设置状态(因为这是异步发生的)。在尝试映射之前检查 this.state 是否已定义:{this.state &amp;&amp; this.state.data.map((x,i)...}

标签: reactjs fetch


【解决方案1】:

DesignName 不是响应中的数组。

你可以这样定义你的状态:

 state = {
    data: null
  }

并使用inline if with logical && operator显示DesignName来解决null问题。

  render() {   
    return (
      <div>
        DesignName: { this.state.data && this.state.data.DesignName}
      </div>
    );
  }

Codesandbox

【讨论】:

  • 谢谢,条件渲染解决了我的问题,数据被this.state.data.DesignName检索到了。
  • 完成。我还需要访问嵌套数据,如果您看到 json 则在 ComponentInfo 内有 ComponentName, FkComponentCategory, PartNumber, Manufacturer, Power, ComponentLevelPassPercentage。我怎样才能访问这些?我试过this.state.data.ComponentInfo.ComponentName 但没用
  • @AnishArya ComponentInfo 是一个数组。您可以通过索引this.state.data.ComponentInfo[0].ComponentName 访问它,或者如果您想显示它们,您可以使用地图。
  • 成功了,如何访问整个数组并显示?
  • @AnishArya 尝试使用地图,我稍后会更新codesandbox。
【解决方案2】:

您可以在等待您的 api 调用完成时使用 isLoading 标志。

state = {
   data: null,
   isLoading:true
}

render() { 
  if(this.state.isLoading) { 
    return(<div>loading</div>); 
  }
  return(
   <ul>
    {this.state.data.map((x,i) => <li key={i}>{x.DesignName}</li>)}
   </ul>
  );

当您的 api 调用完成后,您可以像这样更新状态:

this.setState({ data: findresponse, isLoading:false })

【讨论】:

  • 欢迎来到 Stack Overflow,我赞同这个答案是一个干净的问题解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多