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

react-router replace function not being handled correctly

我在 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函数是明确定义的;但是,路线不会被替换。

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

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