【问题标题】:React.js render json response, co fetch or axiosReact.js 渲染 json 响应,co fetch 或 axios
【发布时间】:2017-09-28 11:15:11
【问题描述】:

我的头发拉得太长了,我无法再集中注意力了。

我正在尝试从 url 获取 json,然后在浏览器中直观地呈现它。它甚至不需要格式化,至少在我克服这个障碍之前不需要。

我可以通过console.log 让它显示在控制台中,但我似乎无法在render 方法中得到响应。我已将其简化为下面的代码,直到我可以在页面上看到某些内容。

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

var co = require('co');
co(function *() {
var res = yield fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow');
var json = yield res.json();
console.log(res);
});

class App extends Component {

render() {
return (
  <div className="App">
    INSERT JSON HERE
  </div>
  );
 }
}

export default App;

我还使用

检索了响应
fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

我最初使用 axios 是因为我想“哦,伙计,我要使用 axios 因为谁很棒?我很棒。”

axios.get('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
  .then(function(response) {
    console.log(response.data);
  });

但那是错误的,因为今天我并不出色。

我会尽我所能!我最初的计划还包括使用 map 来迭代“项目”,如果你能引导我更接近那个区域的救赎,那么可以加分。

【问题讨论】:

  • 我不确定我是否发现了问题。使用 {} 并将其插入 div 有什么问题?
  • 我尝试在渲染方法中放入花括号的所有内容都引发了错误。通常是某种“那个东西没有定义”的错误。
  • axios.get('https://api.stackexchange.com/2.2/search?order=desc&amp;sort=activity&amp;intitle=perl&amp;site=stackoverflow') .then(function(response) { console.log(response.data); }).catch(function(e){console.log(e)}) 这个输出是什么?
  • @luskmonster 因为您的响应在回调之外不存在!将其分配给类属性或将其保存到状态...
  • @ArslArsl Object { items: Array[30], has_more: true, quota_max: 300, quota_remaining: 291 } bundle.js:32919:10 Error: Objects are not valid as a React child (found: object with keys {items, has_more, quota_max, quota_remaining}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of App. bundle.js:11488:16

标签: json reactjs fetch axios co


【解决方案1】:
import React, { Component } from "react";
import axios from "axios";

const URL = "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: []
    }
  }

  componentDidMount() {
    var _this = this;
    axios.get(URL)
    .then(function(res){
      _this.setState({
        items: res.data.items
      });
    })
    .catch(function(e) {
      console.log("ERROR ", e);
    })
  }

  render() {
    const renderItems = this.state.items.map(function(item, i) {
      return <li key={i}>{item.title}</li>
    });

    return (
      <ul className="App">
        {renderItems}
      </ul>
    );
  }
}

【讨论】:

  • 如果您的问题得到解决 - 最好将有助于您的答案标记为解决方案
  • 两种解决方案都非常出色,这是我最终使用的解决方案。谢谢!
  • 很高兴为您提供帮助
  • 出于好奇,为什么var _this = this;
【解决方案2】:

您可以通过 React 的组件状态和生命周期来完成此操作。

在此处阅读:React State/Lifecycle

您可以将 Fetch 调用放在组件的 componentDidMount 函数中,并让回调设置查看状态。

如果您要使用 Fetch,您的组件可能如下所示:

class App extends Component {
 constructor(props) {
  super(props);
  this.state = {
   data: false
  };
  this.receiveData = this.receiveData.bind(this);
 }
 componentDidMount() {
  var _self = this;
  fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
  .then(function(res) {
     return res.json();
  }).then(function(json) {
     console.log(json);
     _self.receiveData(json);
  });
 }
 receiveData(data) {
  this.setState({data});
 }
 render() {
  return <div>{this.state.data}</div>
 }
}

【讨论】:

  • 这绝对是我试图去的地方,当我尝试运行它时,我在控制台中收到以下错误。 Error: Objects are not valid as a React child (found: object with keys {items, has_more, quota_max, quota_remaining}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of 'App'.
  • 哦,不错,抱歉对象不能直接在反应元素中渲染。如果您只想查看数据,您可以&lt;div&gt;JSON.stringify(this.state.data)&lt;/div&gt; 将其打印为字符串以供输出。
  • 我看到了什么!
  • 不错!现在对象处于您的状态,您可以将它传递给孩子的道具,然后用它做其他事情!
猜你喜欢
  • 2022-01-26
  • 2018-04-21
  • 1970-01-01
  • 2018-03-24
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2020-03-25
相关资源
最近更新 更多