Javascript React - 将所有数据从 json 加载到组件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45019420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:52:12  来源:igfitidea点击:

React - load all data from json into component

javascriptjsonreactjsparsing

提问by ChloeH

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 并尝试从本地 json 文件将数据加载到我的组件中。我正在尝试打印所有信息,包括名称:值对(不仅仅是值)中的“名称”,以使其看起来像一个表单。

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.

我正在寻找最好的方法来做到这一点。我需要解析吗?我需要使用地图功能吗?我是 React 的新手,所以请用代码向我展示解决方案。我见过与此类似的其他问题,但它们包含许多我认为不需要的其他代码。

Example of my code: test.json

我的代码示例:test.json

{"person": {
  "name": "John",
  "lastname": "Doe",
  "interests":
  [
    "hiking",
    "skiing"
  ],
  "age": 40
}}

test.js

测试.js

import React, {Component} from 'react';

class Test extends Component {
    render () {
      return (

           ) 
      }
};

export default Test;

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

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

回答by kind user

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

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

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;

回答by Yuri Ramos

The first important question to care about is how you want to get this JSON, if I understood your problem very well it's a local JSON file. So you need to run a local server inside your app to get these values.

要关心的第一个重要问题是您希望如何获取此 JSON,如果我非常了解您的问题,那么它是一个本地 JSON 文件。所以你需要在你的应用程序中运行一个本地服务器来获取这些值。

I'd recommend the live-server, made in node.js.

我推荐使用node.js 制作的live-server

After that you can use axiosto fetch dataand then ...

在此之后,你可以用爱可信获取数据,然后...

import React, {Component} from 'react';
import axios from 'axios';

constructor (props) {
   this.state = {
         items: [],
   }
   axios.get('http://localhost:8080/your/dir/test.json') 
    .then(res => {
        this.setState({ items: res.data });  
   });
}
class Test extends Component {
    console.log(this.state.items);
    render () {
      return (

           ) 
      }
};

export default Test;

I've already put a console.log before render to show your object, and after that do whatever you want!

我已经在渲染之前放置了一个 console.log 来显示你的对象,然后做任何你想做的事!

回答by JakeBoggs

Use JSON.parse(json) Example:

使用 JSON.parse( json) 示例:

JSON.parse(`{"person": {
    "name": "John",

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

回答by Yuhao

Hi the best solution to this is using Axios.

嗨,最好的解决方案是使用 Axios。

https://github.com/mzabriskie/axios

https://github.com/mzabriskie/axios

Try look at their API its very straightforward.

试试看他们的 API,它非常简单。

And yes, you might need a map function to loop the parsed data.

是的,您可能需要一个 map 函数来循环解析数据。

I have a sample code here, which I used Axios.

我这里有一个示例代码,我使用了 Axios。

import axios from 'axios';
const api_key = 'asda99';
const root_url = `http://api.jsonurl&appid=${api_key}`;

export function fetchData(city) {    //export default???
  const url = `${root_url}&q=${city},us`;
  const request = axios.get(url);
}

request is where you get your parsed data. Go ahead and play with it

request 是您获取解析数据的地方。继续玩吧

Heres another example using ES5

这是另一个使用 ES5 的例子

componentDidMount: function() {
    var self = this;

    this.serverRequest =
      axios
        .get("http://localhost:8080/api/stocks")
        .then(function(result) {
          self.setState({
            stocks: result.data
          });
        })

  },

by using the 2nd one. you stored the stocks as a state in here. parse the state as pieces of data.

通过使用第二个。您将股票作为状态存储在这里。将状态解析为数据片段。

回答by Khadim Rana

  • After http://localhost:3001/you type your directory of JSON file: Mydata.json is my JSON file name, you type your file name: Don't forget to import axios on the top. *
  • http://localhost:3001/你输入你的 JSON 文件目录: Mydata.json 是我的 JSON 文件名,你输入你的文件名: 不要忘记在顶部导入 axios。*

componentDidMount() {
    axios.get('http://localhost:3001/../static/data/Mydata.json')
      .then(response => {
      console.log(response.data)
      this.setState({lists: response.data})
    })
 }