React-router v2:如何在回调中使用'replace'函数

时间:2016-02-22 02:15:41

标签: react-router meteor-accounts

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

org.immutables

然而,当它在这样的回调中使用时它会停止工作:

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

<Route path="/" component={App}>
        <Route path="/verify-email/:token" component={AppNotFound} onEnter={verifyEmail}/>
</Route>

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

1 个答案:

答案 0 :(得分:4)

您可能需要传入第三个参数&#34; callback&#34;对于verifyEmail函数,因为该方法是异步的。

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

  

onEnter(nextState,replace,callback?)

     

即将输入路线时调用。它提供了下一个   路由器状态和重定向到另一个路径的功能。这将会   触发挂钩的路由实例。

     

如果将回调列为​​第3个参数,则此挂钩将运行   异步,转换将阻塞,直到回调为止   调用。

所以你的代码应该是:

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
        }
    });
}