React - load all data from json into component

2020-06-16 04:35发布

问题:

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.

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.

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;

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

回答1:

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;


回答2:

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.

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

After that you can use axios to fetch data and 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!



回答3:

Use JSON.parse(json) Example:

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

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


回答4:

Hi the best solution to this is using Axios.

https://github.com/mzabriskie/axios

Try look at their API its very straightforward.

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

I have a sample code here, which I used 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

Heres another example using 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.



回答5:

  • 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. *

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