reactjs - 使用react-router进行基于身份验证的重定向

标签 reactjs react-router

我是 React 新手,在我的项目中我使用了 React-router 来定义路由。但是,我有根据条件重定向的相同路径。我尝试将条件运算符如下所示,但不起作用,也厌倦了 if block 。如何根据条件使用相同的路径渲染不同的组件。

var Routes = (
    <Router history={hashHistory}>
        {role === undefined ? (
            <Route path='/' component={Login} />
            ):
            <Route path='/' component={Home}>
                <Route path='category' component={About}/>
                <Route path='input' component={Cate} />
                <Route path='charts' component={Chart}/>
                <Route path='buyerHome' component={customer}/>
            </Route>
        }
    </Router>
);

最佳答案

您可以使用react-router onEnter hook来保护您的路由。

<Route path='/' component={Home} onEnter={requireAuth}>

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

希望这有帮助。

关于reactjs - 使用react-router进行基于身份验证的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38279555/

相关文章:

angularjs - React 等价于 ng-repeat

javascript - 为什么 React 只允许 HTML 实体的子集?

javascript - CSS Modules 与普通 CSS 在 React 中改变页面背景

javascript - 当 async prop Promise 解析时如何更新 React 组件?

reactjs - URL 更改无需在 React 路由器中重新渲染

javascript - react + ES6 : defaultProps of hierarchy

css - react : background image overlaps navbar

reactjs - React Router - 路径组件未渲染

reactjs - 如何在 React 中链接到另一个页面?

javascript - 尝试使用reactJS将查询字符串参数发送到另一个页面