尝试重置导航会引发错误

时间:2020-03-17 16:44:09

标签: react-native react-navigation expo focuslistener

每次进入特定屏幕(以我的情况为首页)时,我都试图重置导航堆栈。

这是代码段:

componentDidMount(){
        const { navigation } = this.props

        this.focusListener = navigation.addListener('focus', () => {
            this._getData()
            console.log('coucou')
            navigation.dispatch(
                CommonActions.reset({
                  index: 0,
                  routes: [
                    { name: 'Home' },
                  ],
                })
            );
        });
        this._updateNavigationParams()
    }

    componentWillUnmount() {
        // Remove the event listener before removing the screen from the stack
        this.focusListener.remove();
    }

如果删除以下部分,则我的代码可以正常运行:

navigation.dispatch(
                    CommonActions.reset({
                      index: 0,
                      routes: [
                        { name: 'Home' },
                      ],
                    })
                );

我需要一个侦听器,因为当我回到HomeScreen时必须刷新数据,并且每次回到这里时也将使用它来重置导航堆栈。

我得到的错误是:

TypeError:this.focusListener.remove不是一个函数。 (在 'this.focusListener.remove()','this.focusListener.remove'是 未定义)。

1 个答案:

答案 0 :(得分:3)

好,因此网上发现的内容(使用ComponentWillUnmount()函数上的.RemoveListener()或.Remove())不再起作用。

只要看一下React导航文档就可以找到解决方案(here) 我只需要调用用侦听器创建的const。就我而言,我必须像这样修改ComponentWillUnmount

componentWillUnmount() {
    // Remove the event listener before removing the screen from the stack
    this.focusListener();
}