我一直在关注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>
);
Run Code Online (Sandbox Code Playgroud)
当有人未登录时,函数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')
}
});
Run Code Online (Sandbox Code Playgroud)
redirectLocation将设置为'/ login',renderProps将包含下一个状态.但显然在进行服务器端重定向时,nextState不会传递:
res.status(302).redirect(redirectLocation.pathname + redirectLocation.search)
如果这是正确的,那么问题是如何在服务器端重定向时设置状态.
在组件中。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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2419 次 |
| 最近记录: |