gpt4 book ai didi

json - React.js 渲染 json 响应,co fetch 或 axios

转载 作者:行者123 更新时间:2023-12-03 13:58:56 24 4
gpt4 key购买 nike

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

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

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

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 来迭代“项目”,所以如果你能引导我在该领域更接近救赎,那就加分。

最佳答案

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>
);
}
}

关于json - React.js 渲染 json 响应,co fetch 或 axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43712334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com