反应路由器授权

JavaScript React.js

Harry前端神无

2020-03-19

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

我使用react-router 1.x

这是我的路线

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

这是我的仪表板组件:

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>
    );
  }
});

第2313篇《反应路由器授权》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
阿飞番长 2020.03.19

更新了React Router v4的解决方案

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

反应路由器到v3

使用“ onEnter”事件并在回调中检查用户是否被授权:

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

const someAuthCheck = (nextState, transition) => { ... }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android