重定向到屏幕时 componentDidMount 不起作用

Jot*_*nan 1 react-native react-navigation react-lifecycle

我必须componentDidMount在屏幕 A 中列出一组文件(图像),从此屏幕 AI 有另一个屏幕 B 链接,我可以在其中查看文件的详细视图,并且可以选择删除文档。

当使用调用屏幕 A 时

  <TouchableOpacity style={Styles.HomeButton} onPress={ () => this.props.navigation.navigate('Gallery')}>
     <Text style={Styles.HomeButtonText}>View Photos</Text>
  </TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)

componentDidMount 工作正常,但是当我在取消链接回调中删除文件(我正在使用 react-native-fs)时,我正在调用导航

this.props.navigation.navigate('Gallery');
Run Code Online (Sandbox Code Playgroud)

重定向到屏幕 A 工作正常,但componentDidMount无法正常工作,这意味着我仍然可以在列表中看到已删除的文件。即屏幕 A 不刷新,有什么可能的解决方案吗?

小智 6

在 react-navigation 中,如果您导航到其他屏幕,组件将不会卸载,除非您在堆栈导航中重置堆栈。所以当你回到上一个屏幕时,因为它已经安装,componentDidMount不会触发。

您可以绑定一个 react 导航事件侦听器,以在您返回屏幕时触发一些代码。

this.focusListner = this.props.navigation.addListener("didFocus",() => {
  // Update your data
});
Run Code Online (Sandbox Code Playgroud)

卸载组件时不要忘记删除事件侦听器。

componentWillUnmount() {
    // remove event listener
    this.focusListner.remove();
}
Run Code Online (Sandbox Code Playgroud)