javascript - 在 React 中调用 API 后设置状态
问题描述
我正在尝试在 API 调用后设置状态。我正在循环通过 fetch 调用来检索数据,但由于某种原因,如果我 console.log(this) 它将在 this.state.data 中显示我的数据,但如果我 console.log(this.state.data) 或 (this .data) 我有一个空数组。
fetchData = (url, index) => {
fetch(url + index * 100)
.then(response => response.json())
.then(result =>
this.setState({
data: result
}))}
searchChar = () => {
this.setState({
loaded: true,
logo: false,
notFound: false,
})
let value = this.state.basicAddon1.toLowerCase();
const foundSearch = [];
const comics = [];
const url = this.state.url;
const offsetLimit = 5;
const searchIndex = value.charAt(0)
let searchUrl = url.replace("tempKey", searchIndex);
for(let apiSearch = 0; apiSearch < offsetLimit; apiSearch++){
this.fetchData(searchUrl, apiSearch);
console.log(this) - Gets data back if I search the log and go to state and data
console.log(this.state) - Gets undefined
console.log(this.data) - Get undefined
解决方案
所以这里实际上发生了一些事情。
首先,注意你是如何设置this.state.data
结果的。这意味着每次运行此函数时,this.state.data
都会被覆盖。您可能希望将数据转换为对象列表。
其次,注意fetchData
使用 fetch 是异步的。这意味着该函数在返回之前不会等待获取完成。所以会发生什么,在你的循环中,函数运行了几次,在setState
被调用之前,你正在记录。要解决此问题,请等待所有数据解决后再继续。
获取数据
fetchData = async (url, index) => {
await fetch(url + index * 100)
.then(response => response.json())
.then(result =>
this.setState({
data: result // You may want to the replace this line considering the first issue
})
)
}
搜索字符
searchChar = async () => {
...
var dataFetchPromises = []
for(let apiSearch = 0; apiSearch < offsetLimit; apiSearch++){
dataFetchPromises.push(this.fetchData(searchUrl, apiSearch))
await Promise.all(dataFetchPromises)
...
}
推荐阅读
- git - 在 git checkout 分支上,我看到更新文件 (900/112987)
- microsoft-graph-api - msgraph api中的附件大小错误
- javascript - Polarion EventtriggerConfiguration
- django - Django 3:将 URL 中的 slug 传递给视图?
- html - 按钮不会对齐 css/html
- java - 在 Java 中解析 json 字符串的特定元素
- python - 即使文件相等,filecmp 也会返回 False
- wpf - 如何将 StartupEventArgs 传递给 Prism 应用程序中的其他 ViewModel
- azure - Azure Devops - 多项目看板
- datastage - IBM DataStage:作业活动未按顺序继续