React - 将json中的所有数据加载到组件中 [英] React - load all data from json into component

查看:125
本文介绍了React - 将json中的所有数据加载到组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React并尝试从本地json文件将数据加载到我的组件中。我试图打印所有信息,包括名称中的'name':值对(不仅仅是值)使它看起来像一个表单。

I am using React and trying to load data into my component from a local json file. I am trying to print all information, including the 'name' in a name:value pair (not just the value) to make it look like a form.

我正在寻找最佳方法。我需要解析吗?我需要使用地图功能吗?我是React的新手,请告诉我代码解决方案。我已经看到了类似的其他问题,但它们包含了许多我认为不需要的其他代码。

I am looking for the best way to do this. Do I need to parse? Do I need to use a map function? I am new to React so please show me solution with code. I've seen other questions similar to this but they include a lot of other code that I don't think I need.

我的代码示例:
test.json

Example of my code: test.json

"person": {
  "name": John,

  "lastname": Doe,
  "interests": [
    "hiking",
    "skiing"
  ],
  "age": 40
}

test.js

import React, {Component} from 'react';

class Test extends Component {
    render () {
      return (

           ) 
      }
};

export default Test;

我需要能够从json导入的代码和显示所有字段的组件内的代码。

I need code that lets me import from json and code inside component that displays ALL fields.

推荐答案

如果您的json存储在本地,则不必使用任何库来获取它。只需导入它。

If your json is stored locally, you don't have to use any library to get it. Just import it.

import React, {Component} from 'react';
import test from 'test.json';

class Test extends Component {
  render () {
    const elem = test.person;
    return (
     <ul>
       {Object.keys(elem).map((v, i) => <li key={i}>{v} {test[v]}</li> )}
     </ul>
    )
  }
};

export default Test;

这篇关于React - 将json中的所有数据加载到组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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