【问题标题】:Trying to reset navigation throw an error尝试重置导航会引发错误
【发布时间】:2020-06-28 18:55:32
【问题描述】:

每次我到达特定屏幕(在我的例子中是主页)时,我都会尝试重置导航堆栈。

这是一段代码:

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】:

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

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

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

    【讨论】:

    • 你确定吗?我正在阅读文档,它说 this.focusListener.remove() 我遇到了和你一样的问题,但我不确定文档是否正确,我已经用这种方式一年了,之前从未遇到过此错误
    • 我也看到了这个错误。在包的 3.X 版本中,您调用 .remove() 但在较新版本中,您调用原始函数,如上面提到的答案。
    • 使用这两种方法我得到了同样的错误:(有什么解决方案吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 2022-08-02
    相关资源
    最近更新 更多