react-router 4.0 笔记

路由守卫

  • 只有当用户已经登录并拥有某些权限时才能进入某些路由
  • 一个由多个表单组件组成的向导,例如注册流程,用户只有在当前路由的组件填写了满足要求的信息才可以导航 到下一个路由
  • 当用户未执行保存操作而试图离开当前导航时提醒用户
    这是angular都有现成的方法
    苦了react了

react-router实现过程

  • 判断 cookies 是用户是否登陆,没有登陆,返回false
    • 跳转到登陆页
  • 返回true
    • 跳转相应的页面
const AuthExample = () => (
  <Router>
    <div>
      <ul>
        <li><Link to="/public">Public Page</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
      </ul>
      <Route path="/public" component={Public}/>
      <Route path="/login" component={Login}/>
      <PrivateRoute path="/protected" component={Protected}/>
    </div>
  </Router>
)
const PrivateRoute = ({ component: Component, ...abc }) => {
   return  (
  <Route {...abc} render={props => (
    fakeAuth.isAuthenticated ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login'
      }}/>
    )
  )}/>   
)}

fakeAuth 一般都是cookies 或者 localstorage 他是true,那就跳到对应的组件

知识点

  • react-router 4.0+ Route 几种添加组件的方法
  • react-router 路由也是组件
  • 路由跳转的几种方式 Redirect history.push('/')

Prompt

这个好像没有实际作用,表单有没有,react表单都是state绑定

推荐阅读更多精彩内容