用axios渲染json数据

Den*_*sik 2 json reactjs axios

我正在尝试从.json文件中获取数据.页面上没有任何内容.也许有人知道为什么?谢谢!这是文件https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json上的链接

import React from 'react';
import createReactClass from 'create-react-class';
import ReactDOM from 'react-dom';
import axios from 'axios';


class Data extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      array: []
    };
  }

  componentDidMount(){
    axios
      .get('https://crossorigin.me/https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json')
      .then(({ data })=> {
        this.setState({ 
          array: data.recipes.Ingredients
        });
      })
      .catch((err)=> {})
  }

  render() {
    const child = this.state.array.map((element, index) => {
      return <div key={index}>
        <p>{ element.data.name }</p>
      </div>
    });

    return <div><div>{ child }</div></div>;
  }
}

export default Data;
Run Code Online (Sandbox Code Playgroud)

Rav*_*ala 6

这是我给出的练习的答案.我想分享一下,因为你已经尝试过了.这可能有不同的方法.按照自己的方式.这就是我做到的.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import _ from 'lodash';

class Data extends Component {
  constructor(props) {
   super(props);

   this.state = {
     array: []
   };

   this.renderRecipes = this.renderRecipes.bind(this);
 }

 componentDidMount(){
   axios
     .get('https://s3-us-west-2.amazonaws.com/digicode-interview/Q1.json')
     .then(({ data })=> {
       console.log(data);
       this.setState(
         { array: data.recipes }
       );
     })
     .catch((err)=> {})
 }

 render() {
   console.log(this.state.array);
   return(
     <div>
       <h3>Recipes</h3>
       <ul className="list-group">
          {this.renderRecipes()}
       </ul>
     </div>
   );
 }

 renderRecipes() {
   console.log(this.state.array);
   return _.map(this.state.array, recipe => {
     return (
       <li className="list-group-item" key={recipe.name}>
           {recipe.name}
           <ul className="list-group">
              Ingredients:
              {this.renderIngredients(recipe)}
           </ul>
       </li>
     );
   });
 }

 renderIngredients(recipe) {
    return _.map(recipe.Ingredients, ingredient => {
        return (
          <li className="list-group-item" key={ingredient.name}>
              <p>Name: {ingredient.name}, Amount: {ingredient.amount}</p>
          </li>
        );
    });
 }
}

export default Data;
Run Code Online (Sandbox Code Playgroud)