React-router v2:如何在回调中使用“替换”功能

C.L*_*Lee 4 react-router meteor-accounts

在 React-router 中使用“onEnter”属性时,replace()函数在回调中对我不起作用。当它以同步方式(而不是在回调中)调用时,它工作正常:

function verifyEmail(nextState, replace) {
     replace({pathname: '/list'});
}

<Route path="/" component={App}>
        <Route path="/verify-email/:token" component={AppNotFound} onEnter={verifyEmail}/>
</Route>
Run Code Online (Sandbox Code Playgroud)

但是,当它用于像这样的回调时,它会停止工作:

function verifyEmail(nextState, replace) {
    console.log("replace", replace);
    Accounts.verifyEmail( nextState.params.token, function(error){
        if ( error ) {
            console.log(error.reason);
        } else {
            console.log("verified successfully!");
            replace({pathname: '/list'});
        }
    });
}

<Route path="/" component={App}>
        <Route path="/verify-email/:token" component={AppNotFound} onEnter={verifyEmail}/>
</Route>
Run Code Online (Sandbox Code Playgroud)

控制台日志将显示“已成功验证”,但实际上并未重定向页面。

小智 5

您可能需要为 verifyEmail 函数传入第三个参数“回调”,因为该方法是异步的。

请参阅此处的文档:https : //github.com/reactjs/react-router/blob/master/docs/API.md#onenternextstate-replace-callback

onEnter(nextState,替换,回调?)

即将进入路由时调用。它提供下一个路由器状态和重定向到另一条路径的功能。这将是触发钩子的路由实例。

如果回调被列为第三个参数,这个钩子将异步运行,并且转换将阻塞直到回调被调用。

所以你的代码应该是:

function verifyEmail(nextState, replace, callback) {
    console.log("replace", replace);
    Accounts.verifyEmail( nextState.params.token, function(error){
        if ( error ) {
            console.log(error.reason);
            callback(); //When async finishes, do the redirect
        } else {
            console.log("verified successfully!");
            replace({pathname: '/list'});
            callback(); //When async finishes, do the redirect
        }
    });
}
Run Code Online (Sandbox Code Playgroud)