componentDidMount()
中有一个get请求
componentDidMount() {
var manufacturers = []
this.props.participants.map(participant => {
Get("manufacturer/" + participant.id, "").then(result => {
manufacturers.push(result)
console.log(manufacturers)
});
});
this.setState({
participants: manufacturers
})
}
这个console.log(manufacturers)
显示数组中有对象,但组件的状态为空。获取数据后如何正确设置?
Get()
函数代码:
const Config = require('Config')
export async function Get(type, userData) {
let BaseURL = Config.serverUrl;
let result = {};
if(userData)
result = await fetch(BaseURL+type, {
method: 'GET',
headers: new Headers({
'Authorization': 'Bearer ' + userData,
'Content-Type': 'application/json'
})
});
else
result = await fetch(BaseURL+type, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
})
});
let data = await result.json();
return data;
}
最佳答案
由于您要进行多个 Get
调用,并且每个调用都是异步
,因此您必须等到收集到
所有结果然后将其设置为状态。您可以使用 Promise.all
来实现,它可以先等待
所有 Get
调用得到解析,然后将数据设置为状态。
我首先创建一个 async
函数并在 componentDidMount
中调用它。
componentDidMount() {
this.fetchAllData();
}
然后在这个方法中,等待所有Promises
被解析,并在我们获得数据后将其设置为状态。您可能必须将整个函数包装在 try..catch
block 中,以便如果由于网络调用失败而导致任何 Promise 拒绝,您可以适本地处理它。
fetchAllData = async () => {
const manufacturers = await Promise.all(
this.props.participants.map(participant =>
Get("manufacturer/" + participant.id, ""))
)
this.setState(manufacturers)
};
关于javascript - 在ReactJS中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514672/