react-native - 尝试重置导航会引发错误

标签 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 is not a function. (In 'this.focusListener.remove()', 'this.focusListener.remove' is undefined).

最佳答案

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

只看 react 导航文档就给了我解决方案(here) 我只需要调用使用监听器创建的 const 即可。就我而言,我必须像这样修改 ComponentWillUnmount

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

关于react-native - 尝试重置导航会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60726691/

相关文章:

javascript - Expo 和 React Native 有什么区别?最新发布 2018

react-hooks - React Native 的 useNavigation Hook 在自定义 Hook 内?

reactjs - 结合 React 和 React-Native

javascript - React Native : React Navigation StackNavigator not working. 获取错误 : "undefined is not an object (evaluating ' this. props.navigation.navigate')”

react-native - 导航在抽屉​​导航 V3 中的自定义抽屉组件中不起作用( react native )

react-native - Live Reload、Hot Reload 和 Remote Debugging 全部不可用

android - React native/安卓直播播放器

react-native - 使用可独立对齐和附加的 Listview 元素来 react native Listview 网格布局

react-native - React Native Android 权限被拒绝

react-native - 我如何在 native react 中获取路线参数