反应路由器授权

the*_*heo 60 javascript authorization reactjs react-router

在组件安装之前进行授权检查的最佳做法是什么?

我使用react-router 1.x

这是我的路线

React.render((
  <Router history={History.createHistory()}>
    <Route path="/" component={Dashboard}></Route>
    <Route path="/login" component={LoginForm}></Route>
  </Router>
), document.body);
Run Code Online (Sandbox Code Playgroud)

这是我的仪表板组件:

var Dashboard = React.createClass({
  componentWillMount: function () {
    // I want to check authorization here
    // If the user is not authorized they should be redirected to the login page.
    // What is the right way to perform this check?
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

Paw*_*wel 64

针对React路由器v4的更新解决方案

<Route 
  path="/some-path" 
  render={() => !isAuthenticated ?
    <Login/> :
    <Redirect to="/some-path" />
}/>
Run Code Online (Sandbox Code Playgroud)

使路由器达到v3

使用'onEnter'事件并在回调中检查用户是否获得授权:

<Route path="/" component={App} onEnter={someAuthCheck}>  

const someAuthCheck = (nextState, transition) => { ... }
Run Code Online (Sandbox Code Playgroud)

  • 在示例和文档方面,情况变得更糟."auth-flow"示例对我不起作用,并且要找到有关处理程序的第二个参数应该接受的信息并不容易,因此我可以尝试不同的东西. (6认同)
  • 不,不是一个好的解决方案 通常,您会在州内保留有关授权的信息.就像那样,例如:'isAuth:true'.并且您在组件中将此变量作为道具,您只需将其自己传递到您需要的位置即可.但是你不能将任何状态变量传递给'Route'.所以你不得不从'Route'向你的服务器发出'fetch'调用,Ajax请求,以确定用户是否已登录.这是一个无意义和糟糕的设计,有一个简单的状态变量,并使Ajax请求具有相同的目的. (2认同)
  • @Green这里可能有些混乱:你说你应该使用来自州的信息.但是在`onEnter`函数中你可以简单地访问你的简单状态变量(状态是函数的第一个参数),不需要额外的ajax请求 (2认同)
  • 对于那些来自 Google 搜索的内容:“react-router-4”上不再存在“onEnter”。参见:/sf/ask/2993803431/Called-in-react-router (2认同)

Dan*_*ina 5

使用react-router 4,您可以访问组件内的Route道具.要重定向用户,您只需将新URL推送到历史记录即可.在您的示例中,代码将是:

var Dashboard = React.createClass({
  componentWillMount: function () {
    const history = this.props.history; // you'll have this available
    // You have your user information, probably from the state
    // We let the user in only if the role is 'admin'
    if (user.role !== 'admin') {
      history.push('/'); // redirects the user to '/'
    }
  },

  render: function () {
    return (
      <h1>Welcome</h1>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

在文档中,他们通过使用属性而不是使用属性来显示另一种方法.它们定义了一个,当您定义所有路由时,它会使代码非常明确.rendercomponentPrivateRoute