>我有一个状态this.state = { PathBased : [] , ...ect}
还有一个包含for循环的函数,在循环this.state.data
之后,我想将for循环的每个返回元素都添加到PathBased state状态,我找不到该怎么做,你能帮忙吗顺便一提
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
}
您可以使用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)});
}