如何在for循环内的promise中设置状态

时间:2019-02-05 16:04:01

标签: javascript reactjs react-native

我的状态为this.state = { PathBased : [] , ...ect} 和一个包含for循环的函数,在循环this.state.data之后,我想将for循环的每个返回元素添加到PathBased状态, 我找不到方法,请您帮忙

  

console.log(this.state.data)输出为5

async readFromLocal (){
        let dirs = RNFetchBlob.fs.dirs;
        let path = [];
         let leng = this.state.data.length;
          if(leng > 0)
          {
         for( var j = 0 ; j < leng; j++)
         {
          path[j] = dirs.PictureDir+"/folder/"+this.state.data[j].title;

            const xhr = RNFetchBlob.fs.readFile(path[j], 'base64')
            .then ((data) => {this.setState({PathBased:[...PathBased,data]})})
            .catch ((e) => {e.message});
       }

      }
    console.log(this.state.PathBased.length) // output = 0
    }

1 个答案:

答案 0 :(得分:0)

您可以使用Promise.all并将最终结果设置为PathBased状态。另外,由于setState是异步的,因此您需要在setState回调中检查更新后的状态。

async readFromLocal (){
    let dirs = RNFetchBlob.fs.dirs;
    let path = [];
    let promises = [];
    let leng = this.state.data.length;
    if(leng > 0) {
       for( let j = 0 ; j < leng; j++) {
          path[j] = dirs.PictureDir+"/folder/"+this.state.data[j].title;
          promises.push(RNFetchBlob.fs.readFile(path[j], 'base64'))
       }
    }
    Promise.all(promises)
        .then(data => this.setState({PathBased: data}, () => {console.log(this.state.PathBased)})
        )
        .catch(e => {console.log(e.message)});   
}