react-router 路由权限验证几种写法的对比与选择?

由于 react-router 版本更新太快, 网上查了一下关于路由权限的写法有好多种, 但是不知道哪种比较好, 如下

第一种在组件级别上, 直接对对应组件包装一层, 声明为 HOC, 最后渲染的结果为这个组件本身或者一个Redirect, 大致如下

export default function RequireAuth(WrappedComponent) {

  class Authentication extends Component {
    render () {
      if (!this.props.authenticated) {
        return <Redirect to="/" />
      }

      return <WrappedComponent { ...this.props } />
    }
  }

  function mapStateToProps(state) {
    return { authenticated: state.authenticated }
  }

  return connect(mapStateToProps)(Authentication);
}

// 使用
<Route path="/user" component={RequireAuth(User)}/>

第二种是类似于官方推荐的, 在 Route 级别上进行包装, 返回一个 Route 本身或者 Redirect, 代码大致如下:

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    fakeAuth.isAuthenticated === true
      ? <Component {...props} />
      : <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
  )} />
)

// 使用
<PrivateRoute path='/protected' component={Protected} />

第三种是直接进行组合, 将Route作为子组件, 判断是否有权限, 有渲染这个Route, 否则渲染 Redirect, 代码大致如下:

const RequireAuth = ({ children }) => {
  if (!fakeAuth.signedIn) {
    return <Redirect to="/login" />;
  }

  return children;
};

// 使用
<RequireAuth>
  <Route exact path="/dashboard" component={Dashboard} />
</RequireAuth>

写法非常多, 我自己也看的眼花缭乱, 请问对于这些写法该如何取舍, 或者有没有最佳实践? 多谢

阅读 2.7k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题