【问题标题】:react-router replace function not being handled correctly反应路由器替换功能未正确处理
【发布时间】:2016-09-19 08:02:14
【问题描述】:

我已经在onEnter 钩子上调用了这个函数:

function (nextState, replace) {
    var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
        if (!user) {
            console.log('attempting to access a secure route');
            replace({
                pathname: '/login',
                state: { nextPathname: nextState.location.pathname }
            })
            console.log('should have called replace');
        }
        unsubscribe();
    });
};

两个console.log 语句都被执行。 replace 函数是明确定义的;但是,路由不会被替换。

来源问题here,其核心动机略有不同。然而,它们是相关的,但我希望标题不同。

【问题讨论】:

    标签: reactjs firebase react-router firebase-authentication


    【解决方案1】:

    firebase.auth() 是异步的,所以你需要在onEnter 上定义一个回调:

    function (nextState, replace , callback /*** <== add this ***/ ) {
        var unsubscribe = firebase.auth().onAuthStateChanged(function (user) {
            if (!user) {
                console.log('attempting to access a secure route');
                replace({
                    pathname: '/login',
                    state: { nextPathname: nextState.location.pathname }
                })
                console.log('should have called replace');
                callback(); /*** <=== call this to change route ***/
            }
            unsubscribe();
        });
    };
    

    根据文档:https://github.com/ReactTraining/react-router/blob/master/docs/API.md#user-content-onenternextstate-replace-callback

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 2020-07-29
      • 2016-05-15
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 2018-09-07
      • 2019-10-02
      • 2018-01-03
      相关资源
      最近更新 更多