无法在React中访问嵌套的JSON对象 [英] Can't access nested JSON Objects in React

查看:90
本文介绍了无法在React中访问嵌套的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的React组件,并试图在render中显示一个嵌套的JSON对象.

I have a simple React Component, and am trying to display a nested JSON object in render.

// React Component

class NodeDetail extends React.Component {
  constructor(props) {
    super(props);
    const node = {};

    this.state = {
      node
    }
  }

  componentDidMount() {
    Node.getNode(this.props.node_id).then((result) => {
      console.log(result.data);
      this.setState(() => ({node: result.data}));
    }).catch(function(error) {
      // TODO: handle error
    });
  }

  render() {
    return (
      <div>
        {this.state.node.node_status.name}
      </div>
    );
  }
};

export default NodeDetail;

这是从Rails API返回的JSON(存储在result.data中)(为简洁起见,删除了某些字段):

This is the JSON(stored in result.data) getting returned from a rails API(some fields removed for brevity):

{  
   "id":1234,
   "name":"some-node",
   "created_at":"2018-05-18T15:23:24.012Z",
   "hostname":"some-host",
   "ip":"10.XXX.XXX.XXX",
   "mac":"24:6e:96:XX:11:XX",
   "node_status":{  
      "id":2,
      "name":"Parked"
   }
}

当我使用this.state.node.mac访问React中的根级别属性时,它将返回24:6e:96:XX:11:XX.

When I access the root level attributes in React with this.state.node.mac , it returns 24:6e:96:XX:11:XX.

当我尝试使用this.state.node.node_status.name访问node_status中的name属性时,出现以下错误:

When I try to access the name attribute in node_status using this.state.node.node_status.name, I get the the following error:

Uncaught TypeError: Cannot read property 'name' of undefined

我也尝试过this.state.node['node_status'].name,并且出现相同的错误.

I have also tried this.state.node['node_status'].name, and same error.

为什么显然不能在JSON中访问此对象?

Why can't I access this object in the JSON, when clearly it is there?

推荐答案

我敢打赌,这是因为您对Rails API的调用是异步的-因此您的NodeDetail组件会尝试在API返回数据/状态之前进行渲染result.data ...尝试为其他node_status不存在提供条件,如其他一些答案所建议的.

I bet it's because your call to the Rails API is asynchronous -- so your NodeDetail component tries to render before the API returns data / state is set with the result.data...try putting in a condition for non-existent node_status as some of the other answers have suggested.

因此当前(错误的)数据流将是:

So the current (wrong) data flow will be:

  1. constructor. state设置为{node: {}}
  2. componentDidMount.调用API.
  3. render.引发异常,因为this.state.node.node_statusundefined.组件损坏,不会再次呈现...
  4. API返回. state设置为result.data. result.data记录到您的控制台.
  1. constructor. state is set to {node: {}}
  2. componentDidMount. Calls API.
  3. render. Throws exception because this.state.node.node_status is undefined. Component breaks and won't render again...
  4. API returns. state is set to result.data. result.data gets logged to your console.

您可以做的事情是这样的:

What you can do is something like:

render() {
    if (!this.state.node.node_status) {
      return null;
    }

    return (
      <div>
        {this.state.node.node_status.name}
      </div>
    );
  }

或其他任何建议来说明this.state.node.node_statusundefined值.

Or any of the other suggestions to account for the undefined value of this.state.node.node_status.

通常,即使在constructor中设置了默认的state值,也需要确保您的render方法能够正常工作.

In general, you need to make sure that your render method will work, even with the default state values set in your constructor.

这篇关于无法在React中访问嵌套的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆