react-router替换功能未正确处理

时间:2016-05-22 11:58:42

标签: reactjs firebase react-router firebase-authentication

我在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,其核心动机略有不同。但是,它们有点相关,但我希望标题不同。

1 个答案:

答案 0 :(得分:2)

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