更新 React Native 'focus'事件侦听器中的 UI 呈现



我在React Native应用程序中从不同的类对象(屏幕(进行导航。导航到给定的屏幕后,我想执行不同的功能,包括活动指示器,以显示该功能仍在运行。

因此,设置了一个focus事件侦听器,每次我导航回屏幕时都会调用它。我目前的问题是,我的"活动指标"不是在focus事件中更新的,而是直接在之后更新的,这不是我想要的行为,因为我必须等待我的功能在没有任何视觉指标的情况下结束。

class Homescreen extends Component {
constructor(props){
super(props};
this.state = {
showIndicator: false;
}
}
componentDidMount(){
this.props.navigation.addListener('focus', this._onFocus);
}
componentWillUnmount(){
this.props.navigation.removeListener('focus', this._onFocus);
}
_onFocus = async () => {
this.setState({showIndicator: true});
asyncFunc();
};
async asyncFunc(){
//calling a function from swift which calls a C function inside DispatchQeue.main.async
//inside my C function I successfully set my ActivityIndicator to false with an Event which calls
//this.setState({showIndicator: false});
}
render(){
console.log(this.state.showIndicator); // correct value is printed while I wait inside the ```focus``` Event to finish, but the UI is not updated.
return(
{this.state.showIndicator && <ActivityIndicator/>}
)
}
}

我收到了showIndicator的正确当前状态,但在focus事件未完成之前,我的渲染不会重新绘制。对我来说,在我退出focus事件之前,UI似乎不会更新。如何实现在focus事件之前显示ActivityIndicator的目标,或者如何在focus事件之后立即调用函数?

我可以通过使用blur事件来实现我想要的行为,并在移动到另一个屏幕时将我的ActivityIndicator设置为可见,在向后移动后,我等待功能完成并删除ActivityIndicator,但这似乎是一个糟糕的解决方法,而且我在移动时可以看到ActivityIndicator,这可能会令人困惑。

您应该替换此语句周围的大括号{this.state.showIndicator&&}并进行检查。

如果不起作用,请告诉我。

最新更新