【问题标题】:React Native - Callback setstate not work properly in iOSReact Native - 回调 setstate 在 iOS 中无法正常工作
【发布时间】:2018-10-30 04:37:39
【问题描述】:

我有一个模态组件(加载器)并且几乎在每个屏幕上都使用它,但问题是当我 setState 并在 callback setState 中调用 Alert 时它无法正常工作,

这是我的代码:

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>

正如您在else{} 中看到的那样,我处理了callback 以显示alert,但实际结果很奇怪,

我的postLoader 状态仍然是trueAlert 弹出窗口并自行关闭,所以除了在recent apps 中滑动我的应用程序并重新打开外,我什么也做不了,

任何人都知道如何等待 postLoader 状态为 false 然后调用 Alert

【问题讨论】:

  • 为什么PostLoader 管理它自己的可见性?它还在做什么?
  • @Wainage 我只是创建了自己的组件Loader,我不知道代码在android 中有效,但为什么不在iOS 中,我正在使用react native 组件创建我自己的Loader,比如Modal, Image,这就是为什么我做了Modalvisible prop in modal所做的事情

标签: javascript react-native react-native-ios setstate


【解决方案1】:

可以将状态设置为 false,然后显示警告框。当您在 setState 的回调中显示警报时,状态将被更改,但组件不会重新呈现自身。试试这个,

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>

【讨论】:

    【解决方案2】:

    您可以使用 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>
    

    【讨论】: