使用axios渲染json数据 [英] Rendering json data with axios

查看:117
本文介绍了使用axios渲染json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get data from .json file. Nothing appears on the page. Maybe somebody have an idea why? Thanks! This is link on the file 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;

推荐答案

这是我对给定练习的答案.我想分享一下,因为您已经尝试过了.可能有不同的方法来执行此操作.按照自己的方式.这是我的方法.

Here's my answer to the exercise given. I would like to share this, since you have tried that out. There may be different ways of doing this. Follow your own way. Here's how I did it.

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;

这篇关于使用axios渲染json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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