【问题标题】:redux how to redirect on componentWillMount using react-routerredux如何使用react-router在componentWillMount上重定向
【发布时间】:2015-12-15 08:57:15
【问题描述】:

如何使用 react-router 在 componentWillMount 上重定向

export class NewStock extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  componentWillMount() {
    const { session, dispatch, router } = this.props
    if (session.userSessionData.get('logged_in') == false) {
      router.transitionTo('/login')
    }
  };

这段代码:

router.transitionTo('/login')

只返回:

Uncaught TypeError: router.transitionTo is not a function

【问题讨论】:

  • 我只看到了从 Router.Navigation mixin 中使用 transitionTo() 的示例。你需要添加那个mixin,然后你就可以说this.transitionTo(...)
  • 还有一件事,可能最好在 willTransitionTo 静态回调上以编程方式进行转换。这将阻止您的视图在调用您的 transitionTo() 之前短暂可见。

标签: javascript reactjs redux react-router


【解决方案1】:

试试this.props.history:

const { history } = this.props
history.pushState(null, '/login') or
history.replaceState(null, '/login')

如果您的模块不是路由器的直接后代,您仍然可以通过将组件包装在 withRouter(YourComponent) HOC(在 v4 中)中来访问此属性。

【讨论】:

  • 对我来说,我得到Cannot read property 'pushState' of undefined。好像我的组件没有上下文。 (使用相同的定义和构造函数)
  • 我必须道歉,我没有意识到这是 redux。我正在做通量自动取款机。所以我无论如何都不能为我工作。
  • 道歉我很困惑实际上它不是特定于 redux - 历史被传递给路由器,它应该在上下文中提供,例如- <Router history={browserHistory}>{routes}</Router>
【解决方案2】:

我正在做的是使用路由的 onEnter 属性。这使我可以更好地集中我的身份验证。我的灵感来自the react-router examples

我来到这里是因为我和你一样摸索着,但很快就陷入了一大堆难以管理的代码中。

希望所有来到这里的人都能从我的错误中吸取教训。

function requireAuth(nextState, replace) {
    if (!UserStore.userIsSignedIn()) {
        replace({
            pathname: '/login',
            state: {nextPathname: nextState.location.pathname}
        })
    }
}

render((
    <Router history={hashHistory}>
        <Route path="/" component={PageHeader}>
            <IndexRoute component={AssignmentOverview} onEnter={requireAuth}/>
            <Route path="login" component={UserLoginForm}/>
            <Route path="logout" component={UserLogout}/>
            <Route path="profile" component={UserProfile} onEnter={requireAuth}/>
            <Route path="assignmentform" component={AssignmentForm} onEnter={requireAuth}/>
        </Route>
    </Router>
), document.getElementById('content'));

【讨论】:

  • 我喜欢使用高阶组件来包装所有需要身份验证的页面。您的方法的问题是可以在未经身份验证的情况下查看身份验证页面。只需注销而不重定向。我更喜欢 componentDidMount + componentWillReceiveProps。如果在页面上的身份验证发生变化,我仍然会被重定向,并且我不需要在每个注销按钮中都放置重定向登录。
  • v4 更新:onEnter 属性已删除,文档建议改用 componentWillMountsource
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 2016-10-23
  • 2020-09-02
  • 2018-01-05
  • 2018-02-18
  • 2019-07-30
相关资源
最近更新 更多