te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Can't access nested JSON Objects in React - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can't access nested JSON Objects in React - Stack Overflow

programmeradmin4浏览0评论

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

  ponentDidMount() {
    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;

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"
   }
}

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

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

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

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

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

  ponentDidMount() {
    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;

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"
   }
}

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

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

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

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

Share Improve this question asked May 18, 2018 at 19:14 grizzthedjgrizzthedj 7,50517 gold badges46 silver badges65 bronze badges 4
  • What does this.state.node.node_status return? – Asons Commented May 18, 2018 at 19:21
  • @LGSon this.state.node.node_status returns undefined. But it is actually present. Verified this with console.log(result.data); – grizzthedj Commented May 18, 2018 at 19:23
  • And as a test, what if you only grab the node_status, like this, this.setState(() => ({node: result.data.node_status})); and then do this.state.node.name – Asons Commented May 18, 2018 at 19:30
  • Given @user's answer below, when you tried this.state.node.mac (which you wrote worked), did you do that within the render method as well? – Asons Commented May 18, 2018 at 19:40
Add a ment  | 

4 Answers 4

Reset to default 6

I bet it's because your call to the Rails API is asynchronous -- so your NodeDetail ponent 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 is set to {node: {}}
  2. ponentDidMount. 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>
    );
  }

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

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

Error is ing correct Your are fetching data after ponent loaded In short you are calling your API in ponentDidMount You can get rid off from this error in this way

 <div>
        {this.state.node.node_status?this.state.node.node_status.name:""}
 </div>

and I would suggest you to call fetch data API in ponentWillMount or constructor which is the initial stage of ponent.

In render

newsapi_news.spacy_tags is an [object object]

newsapi_news.spacy_tags.all_tags THROWS can not read prop of undefined error

But this will work

data-tag={(newsapi_news.spacy_tags) ? newsapi_news.spacy_tags.all_tags : ""}

Code in render must be "piled" or mounted or whatever the term is and the parent element is not defined yet but the parent of the parent is

Only solution that worked for me: https://stackoverflow./a/51175467

Issue is that JSON objects can be accessed one-level deep before they are populated, so it is not breaking your webpage until you try to access a nested attribute.

发布评论

评论列表(0)

  1. 暂无评论