在 react-router 2.4.0 中重定向 willTransitionTo?

IT技术 reactjs react-router
2021-05-01 13:59:24

我目前正在"react-router": "^2.4.0"我的聊天应用程序上使用,并且对如何在没有用户时重定向感到困惑。我不认为重定向"^2.4.0".

我应该onEnter在我的聊天路径使用钩子吗?

像这样的东西:

 <Route path="chat" component={Chat} onEnter={Chat.willTransitionTo}/>

路由.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');
  }
}
2个回答

我使用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
};

至少有一个拼写错误:

tansition.redirect('/login');

应该:

transition.redirect('/login');

您还应该检查 react-router 的 auth-flow 示例:https : //github.com/reactjs/react-router/tree/master/examples/auth-flow