【问题标题】:Unable to render the JSON Object on browser in React.js无法在 React.js 中的浏览器上呈现 JSON 对象
【发布时间】:2017-01-07 23:13:50
【问题描述】:

我正在尝试显示一个 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": ""
  }
]

非常感谢任何有关显示数据的帮助。

【问题讨论】:

    标签: javascript json reactjs for-loop


    【解决方案1】:

    这里有 3 个错误...

    第一:
    &lt;h1&gt; temp.article_id &lt;/h1&gt; 不会打印文章 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>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      相关资源
      最近更新 更多