【问题标题】:React-Native app async data retrive not working properlyReact-Native 应用程序异步数据检索无法正常工作
【发布时间】:2020-04-12 02:13:36
【问题描述】:

我将componentDidMount方法作为async使用并进行了一些操作,但是系统返回给我的是第一个条目的状态而不是异步工作。

  async componentDidMount() {
    await this.getCityList();
    console.log(this.state.cities)
    await this.currentLocation();
  }

此时控制台日志变为空。但是,当我通常检查时,会观察到数据输入,但会在一段时间后出现。这同样适用于 currentloc 方法。这些方法从数据库中提取一些数据。

和城市功能:

  getCityList() {
    let link = "http://..../Cities";
    fetch(link)
      .then(response => response.json())
      .then(res => {
        this.setState({
          cities: res,
        })
      })
      .catch(error => console.warn(":::::::::", error));
  }

【问题讨论】:

    标签: c# react-native promise async-await


    【解决方案1】:

    您需要在getCityList 方法中返回Promise。

    没有return

    async function foo() {
      const result = await baz();
      console.log('Result', result);
    
      console.log('Should be called after baz!');
    }
    
    function baz() {
      new Promise((resolve) => {
        setTimeout(() => resolve('Hello from baz!'), 3000);
      });
    }
    
    foo();

    return

    async function foo() {
      const result = await baz();
      console.log('Result', result);
    
      console.log('Should be called after baz!');
    }
    
    function baz() {
      return new Promise((resolve) => {
        setTimeout(() => resolve('Hello from baz!'), 3000);
      });
    }
    
    foo();

    以下是使await 工作的正确方法(使用您的示例 sn-p):

     getCityList() {
        let link = "http://..../Cities";
        return fetch(link) // Added a return here
          .then(response => response.json())
          .then(res => {
            this.setState({
              cities: res,
            })
          })
          .catch(error => console.warn(":::::::::", error));
      }
    

    【讨论】:

    • 它解决了我一半的问题,但我无法解决其他部分。我的 2. 函数正在使用 google API 和嵌套函数,我如何在那里使用? link
    • @ArtunBurakMecik 我建议为此创建一个单独的问题。您可以将我链接到此处的问题。
    猜你喜欢
    • 2020-04-12
    • 1970-01-01
    • 2018-06-13
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多