尝试重置导航会引发错误

Ale*_*dre 2 focuslistener react-native react-navigation expo

每次到达特定屏幕(在我的情况下,主页)时,我都试图重置导航堆栈。

这是一段代码:

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();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

我得到的错误是:

类型错误:this.focusListener.remove 不是函数。(在 'this.focusListener.remove()' 中,'this.focusListener.remove' 未定义)。

Ale*_*dre 5

好的,那么在网上找到的(在 ComponentWillUnmount() 函数上使用 .RemoveListener() 或 .Remove() )不再有效。

只是看一下反应导航文档就给了我解决方案(这里)我只需要调用用侦听器创建的常量。在我的情况下,我必须像这样修改 ComponentWillUnmount

componentWillUnmount() {
    // Remove the event listener before removing the screen from the stack
    this.focusListener();
}
Run Code Online (Sandbox Code Playgroud)