我一直关注react-router 1.0.3的auth-flow示例:
var requireAuth = function(nextState, replaceState){
if(!auth.loggedIn()){
replaceState({ nextPathname: nextState.location.pathname }, '/login');
}
}
export default (
<Route component={App}>
<Route path='/login' component={Login}/>
<Route path='/' component={Messenger} onEnter={requireAuth}/>
</Route>
);
当某人未登录时,函数replaceState按预期执行,显示/ login页面,但状态为:
{ nextPathname: nextState.location.pathname }
应该在this.props.location.state中找不到它。相反,this.props.location.state未定义。
这似乎与以下问题相同: https://github.com/rackt/react-router/issues/2768
有人知道为什么国家没有被设定?
修改 我试过this.props.history.replaceState,似乎没有问题地传递状态。它只在onEnter挂钩时才起作用。
编辑2 经过实验和学习更多关于反应的知识,我意识到我正在做反应的服务器端渲染。 replaceState函数将在服务器中触发,并且Router.match函数(建议用于服务器端呈现)将触发:
Router.match({ routes: routes.default, location: req.url }, function(err, redirectLocation, renderProps) {
if (err) {
res.status(500).send(err.message)
} else if (redirectLocation) {
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
var html = ReactDOM.renderToString(React.createElement(Router.RoutingContext, renderProps));
var page = swig.renderFile('views/index.html', { html: html });
res.status(200).send(page);
} else {
res.status(404).send('Page Not Found')
}
});
redirectLocation将设置为'/ login',renderProps将包含下一个状态。但显然在进行服务器端重定向时,nextState不会传递:
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
如果这是正确的,那么问题是如何在服务器端重定向时设置状态。
答案 0 :(得分:0)
在组件中。 pathName位于this.props.location.pathname中 我明白了。
_handleSubmit: function(e) {
e.preventDefault();
//console.log(this.props.location.state); // null ???
//the above should be changed to
console.log(this.props.location.pathname);
return false;
}