【问题标题】:React-native put values in state with fetch in a loopReact-native 将值置于循环中获取状态
【发布时间】:2017-10-31 09:03:13
【问题描述】:

我想使用 google API 获得几次旅程的持续时间,但我无法将获得的值放入我的状态。 这是我的代码:

for (i = 0; i < this.state.nbLieux; i++) {
        const index = i;
        fetch(`https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&mode=walking&origins=${this.state.location.coords.latitude},${this.state.location.coords.longitude}&destinations=${this.state.lieux[index].lattitude},${this.state.lieux[index].longitude}&key=AIzaSyBqonK_W7A4chMiVoJTTs2cTU65XBcCh68`)
        .then((response) => response.json())
        .then((responseJson) => {
            Duree[index] = responseJson.data
        })
        .catch((error) => {
            console.warn(error);
        })
        .done();
    }
    this.setState({Duree});
    console.log('salut'+JSON.stringify(this.state.Duree));

谢谢!

编辑

this.myFunction().then((Duree) => { 
            console.log(Duree)
        });

myFunction() {
    return new Promise((resolve, reject) => {
        let fetches = [];
        let Duree = [];
        for(let i = 0; i < this.state.nbLieux; i++) {
            fetches.push(
                fetch(`https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&mode=walking&origins=${this.state.location.coords.latitude},${this.state.location.coords.longitude}&destinations=${this.state.lieux[i].lattitude},${this.state.lieux[i].longitude}&key=AIzaSyBqonK_W7A4chMiVoJTTs2cTU65XBcCh68`)
                .then((response) => response.json())
                .then((responseJson) => {
                    console.log(JSON.stringify(responseJson));
                    Duree[i] = responseJson;
                }).catch((error) => {
                    console.warn(error);
                }).done()
            )
        }
        Promise.all(fetches).then(() => {
            resolve(Duree);
        })
    });
}

但在控制台中我可以看到第一个 console.log 在第二个之前执行...

【问题讨论】:

    标签: loops asynchronous react-native fetch state


    【解决方案1】:

    将其包装在 Promise 中,并为 es6 使用 LET 关键字或为 es5 使用闭包。就这样……

        myFunction() {
        return new Promise((resolve, reject) => {
    
          let fetches = [];
          let arr = [];
    
          for(let i = 0; i < 20; i++) {
            fetches.push(
                fetch("https://slack.com/api/api.test")
            .then((data) => data.json())
            .then((dataJson) => {
              arr[i] = dataJson;
            })
            )
          }
    
          Promise.all(fetches).then(() => {
            resolve(arr);
          })
    
        });
       }
    
       myFunction().then((data) => {
           console.log(data);
       })
    

    测试了一个作品就好了。这是 Chrome 中的 console.log...

    另外,请确保“nbLieux”的状态没有改变。如果是,请在 for 循环上方使用另一个 let 变量:“let num = this.state.nbLieux”

    【讨论】:

    • 嗨 VocoJax,感谢您的回答,我尝试了您的代码,但该州有一个空数组。查看我的编辑,看看我尝试了什么。
    • 我编辑了我的答案。它根本没有改变,但我已经测试过它并且它有效。你的 api 字符串可能坏了吗?
    猜你喜欢
    • 2020-11-18
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    相关资源
    最近更新 更多