Rag*_*san 5 reactjs react-router
我目前正在使用"react-router": "^2.4.0"我的聊天应用程序,并且在没有用户时如何重定向感到困惑.我不认为重定向的作品"^2.4.0".
我应该onEnter在聊天路径上使用挂钩吗?
像这样的东西:
<Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>
Run Code Online (Sandbox Code Playgroud)
routes.js
<Route path="/" component={App} >
<IndexRoute component={Chat} />
<Route path="chat" component={Chat} />
<Route path="login" component={Login} />
</Route>
Run Code Online (Sandbox Code Playgroud)
Chat.jsx
static willTransitionTo(transition){
var state = ChatStore.getState();
if(!state.user){
transition.redirect('/login');
}
}
Run Code Online (Sandbox Code Playgroud)
我通过使用它使其工作,setRouteLeaveHook如下所示:
https: //github.com/ReactTraining/react-router/blob/master/docs/guides/ConfirmingNavigation.md
返回 false 以防止不提示用户的转换
我们可以使用它来实现我们自己的解决方案,如下所示:
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
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2427 次 |
| 最近记录: |