尝试重设导航会引发错误

问题描述 投票:0回答:1

每次进入特定屏幕(在我的情况下,是主页),我都会尝试重置导航堆栈。

这是一段代码:

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'是未定义)。

react-native react-navigation expo focuslistener
1个回答
0
投票

确定,因此在网上找到的内容(使用ComponentWillUnmount()函数上的.RemoveListener()或.Remove())不再起作用。

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

componentWillUnmount() {
    // Remove the event listener before removing the screen from the stack
    this.focusListener();
}
© www.soinside.com 2019 - 2024. All rights reserved.