问题描述
我目前在我的聊天应用程序上使用 "react-router": "^2.4.0"
并且对如何在没有用户时重定向感到困惑.我认为 redirect 在 "^2.4.0"
中不起作用.
I am currently using "react-router": "^2.4.0"
on my chat application and confused on how to redirect when there is no user. I don't think redirect works in "^2.4.0"
.
我应该在我的 聊天 路径上使用 onEnter
挂钩吗?
Should I use onEnter
hooks on my chat path?
类似这样:
<Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>
routes.js
<Route path="/" component={App} >
<IndexRoute component={Chat} />
<Route path="chat" component={Chat} />
<Route path="login" component={Login} />
</Route>
Chat.jsx
static willTransitionTo(transition){
var state = ChatStore.getState();
if(!state.user){
transition.redirect('/login');
}
}
推荐答案
我通过使用 setRouteLeaveHook
使它工作,因为它在这里说:https://github.com/ReactTraining/react-路由器/blob/master/docs/guides/ConfirmingNavigation.md
I made it work by using setRouteLeaveHook
as it says here:https://github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md
返回 false 以防止没有提示用户的转换
然而,他们忘记提到钩子也应该被取消注册,参见这里 和 noreferrol">.
However, they forget to mention that the hook should be unregistered as well, see here and here.
我们可以使用它来实现我们自己的解决方案,如下所示:
We can use this to implement our own solution as follows:
class YourComponent extends Component {
constructor() {
super();
const {route} = this.props;
const {router} = this.context;
this.unregisterLeaveHook = router.setRouteLeaveHook(
route,
this.routerWillLeave.bind(this)
);
}
componentWillUnmount() {
this.unregisterLeaveHook();
}
routerWillLeave() {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
if (!this.state.isSaved) {
return 'Your work is not saved! Are you sure you want to leave?'
}
}
...
}
YourComponent.contextTypes = {
router: routerShape
};
这篇关于在 react-router 2.4.0 中重定向 willTransitionTo?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!