我把头发拉得太久了,我无法集中注意力了。
我正在尝试从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);
});
但这是一个谬误,因为今天我并不出色。
我将竭尽所能!我最初的计划还包括使用地图来迭代“项目”,所以如果您能引导我更接近该地区的救赎,您可以加分。
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>
);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句