我正在尝试访问 API,并在图表中显示数据。我已经遵循了使用 Fetch 的教程;例如这个: (https://appdividend.com/2018/08/20/javascript-fetch-api-example-tutorial/)
fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json())
.then(json => console.log(json));
这很可爱,它获取数据并将其记录到控制台中。但据我所知,数据在外部不可用,如何将 console.log(json)
内显示的数据获取到状态,以便我可以将其呈现在图表中?
最佳答案
将响应分配给变量,然后使用数据调用 setState
,如下所示:
使用异步更新
const response = await fetch('https://api.github.com/users/KrunalLathiya')
.then(res => res.json());
this.setState({
data: response
});
然后您可以在图形的渲染中使用 this.state.data
访问您的响应。
关于javascript - 如何在状态中使用来自 Fetch 请求的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55381114/