首页 > 解决方案 > React Native - Callback setstate not work properly in iOS

问题描述

I have a modal component (loader) and used it almost on every screen, but the problem is when I've setState and calling Alert in callback setState it's not work properly,

here's my code:

LoginProcess(){
this.setState({postLoader:true})
//calling API and handle if the password is wrong, showing alert
  if(response.ok && response.status == 200){
    //navigate to home
  } else {
    this.setState({postLoader:false},()=>Alert.alert("Perhatian", "Password salah!\nSilahkan coba kembali"))
  }
}

<View>
  <PostLoader showModal={this.state.postLoader} nameLoader="Mengirim data"/> //the loader using modal
</View>

as you can see in else{} I've handle the callback to show alert, but the actual result is strange,

enter image description here

my postLoader state is still true and the Alert popup and close itself, so i can't do anything except swipe my app in recent apps and reopen,

anyone has an idea how to wait postLoader state to false then call Alert?

标签: javascriptreact-nativereact-native-iossetstate

解决方案


您可以使用 setTimeout,它将在 this.setState 之后指定的 ms(毫秒)之后执行,并将根据需要工作。

LoginProcess(){
this.setState({postLoader:true})
//calling API and handle if the password is wrong, showing alert
  if(response.ok && response.status == 200){
    //navigate to home
  } else {
    this.setState({postLoader:false})
    setTimeout(() => {
    Alert.alert("Perhatian", "Password salah!\nSilahkan coba kembali")
    }, 100);
  }
}

<View>
  <PostLoader showModal={this.state.postLoader} nameLoader="Mengirim data"/> //the loader using modal
</View>

推荐阅读