好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

React路由拦截模式及withRouter示例详解

一、路由拦截

在前面两篇 路由博客基础上,我们将 ReactRouter.js 的我的 profile 路由设置成路由拦截的:

<Route path="/profile" render={() => 
                isAuth() ? <Profile/> : <Redirect to="/login"></Redirect>
              }></Route>

新建 Login.js 组件,写入代码:

import React, { Component } from 'react'

export default class Login extends Component {
  render() {
    return (
      <div>
          <h2>Login</h2>
          <input type="text"></input>
          <button onClick={() => {
              localStorage.setItem('token', 123  )
              this.props.history.push('/profile')
          }}>模拟登录</button>
      </div>
    )
  }
}

效果:

二、路由模式

之前带 # 号的路由模式为哈西模式,如果想不带 # 号的话,可以写成如下:

但是 BrowserRouter 没有 # 路径,后端如果没有对应的路径处理逻辑,就会404。

三、withRouter

如果我们在我的页面里面还有我的订单路由的话,那么在 Profile.js 中写入跳转的语法:

import React from 'react'

export default function Profile(props) {
  return (
    <div>
        <h1>Profile</h1>
        <div onClick={() => {
          props.history.push('/profileorder')
        }}>我的订单</div>
      </div>
  )
}

可以看到报错了,那我们之前那种写法不生效了吗。其实跟路由的创建有关系,之前是直接将组件用 component 属性直接传了过去,所以 props 有 history 对象,但是这次我们是采用的 render 将组件在立即函数中实例化了,不传进去:

所以在这里 props 接收不到任何东西,是非常正常的。在使用 render 的路由时,我们可以这样传参:

通过传 props 那么子组件中将有路由的一些属性,就可以做跳转。如果在路由组件上不传 props 的话,那么将使用 withRouter 进行跳转。将 props 删除:

可以看到即使 render 的路由父组件不传 props ,我们使用 withRouter ,也能够进行路由的跳转。

以上就是React路由拦截模式及withRouter示例详解的详细内容,更多关于React路由拦截模式withRouter的资料请关注其它相关文章!

查看更多关于React路由拦截模式及withRouter示例详解的详细内容...

  阅读:41次