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

时间:2017-07-10 18:36:48

标签: javascript json reactjs parsing

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

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

我的代码示例: 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导入的代码和显示所有字段的组件内的代码。

6 个答案:

答案 0 :(得分:9)

如果您的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;

答案 1 :(得分:8)

要关注的第一个重要问题是如何获得此JSON,如果我非常了解您的问题,那么它就是本地JSON文件。因此,您需要在应用程序中运行本地服务器才能获得这些值。

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

之后,您可以使用axios 获取数据然后...

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;

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

答案 2 :(得分:1)

使用JSON.parse( json ) 例如:

NULL

答案 3 :(得分:0)

对此最好的解决方案是使用Axios。

https://github.com/mzabriskie/axios

尝试看看他们的API非常简单。

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

我这里有一个示例代码,我使用了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);
}

请求是获取解析数据的地方。继续玩吧

另一个使用ES5的例子

componentDidMount: function() {
    var self = this;

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

  },

使用第二个。你把股票存放在这里的状态。将状态解析为数据片段。

答案 4 :(得分:0)

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

答案 5 :(得分:0)

如果要通过HTTP加载文件,则可以使用内置的window.fetch()函数(在最近几年的浏览器中,请参阅Mozilla's developer pages以获取兼容性支持)。

fetch("https://api.example.com/items")
  .then(res => res.json())

React文档介绍了其他Ajax requests的处理方式(即来自已加载网页的请求)。

如果您的JSON在本地文件中,请按照其他人的解释将其导入:

import test from 'test.json';