【发布时间】: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&sort=activity&intitle=perl&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 ofApp. bundle.js:11488:16
标签: json reactjs fetch axios co