【问题标题】:fetch/axios async/await request freeze app in react nativefetch/axios async/await request freeze app in react native
【发布时间】:2018-10-25 03:05:30
【问题描述】:

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

【问题讨论】:

  • data 定义在哪里?
  • 您在设备上运行吗?如果是这样,当您禁用远程调试时会发生什么?另外,data 中有多少元素?
  • console.log(2) 几乎紧跟在console.log(1) 之后的输出(应该是)
  • @Bravo 是的,但是当我按下“测试 2”按钮时不会立即显示日志(3)

标签: javascript react-native asynchronous async-await fetch


【解决方案1】:

最后我找到了使用下一帧的解决方案:

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

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2018-12-23
    • 2021-05-10
    • 1970-01-01
    • 2018-12-06
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多