Reactjs 在react路由器2.4.0中重定向到?
我目前正在聊天应用程序上使用Reactjs 在react路由器2.4.0中重定向到?,reactjs,react-router,Reactjs,React Router,我目前正在聊天应用程序上使用“react router”:“^2.4.0”,对没有用户时如何重定向感到困惑。我认为重定向在“^2.4.0”中不起作用 我应该在我的聊天路径上使用onEnter钩子吗 类似这样的内容: <Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/> 至少有一个拼写错误: tansition.redirect('/login'); 应该是: transition.redire
“react router”:“^2.4.0”
,对没有用户时如何重定向感到困惑。我认为重定向在“^2.4.0”
中不起作用
我应该在我的聊天路径上使用onEnter
钩子吗
类似这样的内容:
<Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>
至少有一个拼写错误:
tansition.redirect('/login');
应该是:
transition.redirect('/login');
您还应该检查react router的auth flow示例:我使用
setRouteLeaveHook
实现了它,正如它在这里所说的:
返回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
};
似乎WillTransitiono在1.0中已经被弃用,取而代之的是OneNet:github.com/reactjs/react router/releases?after=v1.0.2
transition.redirect('/login');
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
};