繁体   English   中英

无法在React.js中的浏览器上呈现JSON对象

[英]Unable to render the JSON Object on browser in React.js

我试图显示一个JSON对象,它是React中的一个数组。 我能够编写React代码来做到这一点。 但是,我无法在浏览器中看到输出。

这是我的代码:

import React, {Component} from 'react';
import data from '../articles';
export default class fetchData extends Component {
  showData = (inputValue) => {
    inputValue.forEach((temp) => {
      return (
        <h1> temp.article_id </h1>
      );
    });
  }
  render () {
    return (
      <h1> {this.showData(data)} </h1>
    );
  }
}

JSON对象:(位于../articles

[
  {
    "article_id": "101",
    "org_id": "10001",
    "reported_by": "Srilakshmi",
    "reported_on": "11-16-2016",
    "author": "Sree",
    "language": "English",
    "src_url": "",
    "key_words": "CS, Programming",
    "status": "Draft",
    "channel_ids": "IOE1",
    "title": "CS 101 Lession",
    "description": "CS 101 First Lession",
    "file_on_disk": "",
    "publish_on": "",
    "Published_on": "",
    "contentArray": ""
  },
  {
    "article_id": "102",
    "org_id": "10001",
    "reported_by": "Srini",
    "reported_on": "11-16-2016",
    "author": "Srini",
    "language": "English",
    "src_url": "",
    "key_words": "CS, DB",
    "status": "Draft",
    "channel_ids": "IOE2",
    "title": "CS DB 101 Lession",
    "description": "CS DB 101 First Lession",
    "file_on_disk": "",
    "publish_on": "",
    "Published_on": "",
    "contentArray": ""
  }
]

我们非常感谢您提供有关显示数据的任何帮助。

这里有3个错误...

第一:
<h1> temp.article_id </h1>不会打印文章ID。 使用花括号打印实际值

<h1>{ temp.article_id }</h1>

第二:
forEach数组方法只是循环数组,它不会根据回调中返回的值创建新的数组。 请改用map方法。

inputValue.map((temp) => {
    return (
        <h1> temp.article_id </h1>
    );
});

第三
您根本不会从showData方法返回。 编辑代码以返回新创建的组件数组(使用map方法创建的数组)

showData = (inputValue) => {
    return inputValue.map((temp) => {
        return (
            <h1>{ temp.article_id }</h1>
        );
    });
}

奖金:
使用箭头功能使其简短

showData = (inputValue) =>
    inputValue.map(temp => <h1>{ temp.article_id }</h1>)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM