当请求API时,我的应用程序出现了一些问题。我的问题如下:
等待应用程序请求时,应用程序将完全冻结,并且仅在请求完成后才触发设置选项卡或“测试2”按钮上的单击事件。如果有人遇到同样的问题并找到解决方法 请回答,谢谢!
class HomeScreen extends React.Component {
state = {
isLoading: false
}
fetchData = () => {
console.log('1');
this.setState({isLoading:true});
// await Promise.all(
data.map(async (x) => {
await axios.get(x.url);
})
// )
console.log('2');
this.setState({isLoading:false})
}
renderLoading = () => {
if (this.state.isLoading) {
return <ActivityIndicator size={40} />
}
return null
}
test2 = () => {
console.log('3');
}
render() {
return (
<View style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center' }}>
{this.renderLoading()}
<TouchableOpacity style={{height: 50}} onPress={() => this.fetchData()}><Text>Test</Text></TouchableOpacity>
<TouchableOpacity style={{height: 50}} onPress={() => this.test2()}><Text>Test 2</Text></TouchableOpacity>
</View>
);
}
}
答案 0 :(得分:0)
最后我找到了使用下一帧的解决方案:
let queue = Promise.resolve();
data.forEach(x => {
queue = queue.then(() => nextFrame().then(async () => {
const response = await fetch(x.url);
const content = await response.text();
console.log(content);
}));
});
queue.then(() => {
console.log('complete!');
this.setState({isLoading:false})
});