react-router 的使用

逆战班

本教程前提是你的应用程序是一个web应用程序,使用’react-router-dom‘包来实现页面的路由

在React router中有三种类型的组件

  1. 路由组件: BrowserRouter 和 HashRouter
  2. 路径匹配的组件: Route 和 Switch
  3. 导航组件: Link

官方文档地址:
https://reacttraining.com/react-router/web/guides/philosophy

安装

npm install react-router-dom

简单用法

import React from 'react';
import './App.scss';

import Home from "./components/home";
import Sort from "./components/sort";
import Shop from "./components/shop";
import Mine from "./components/mine";
import NotFound from './components/notfound'
import { Route, NavLink, Redirect, Switch, withRouter } from 'react-router-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: true
    }
  }
  componentDidMount() {
    this.changeTitle(this.props.location.pathname); //解决刷新问题的
    this.routeListen();  //组件一挂载就监听,  为了用setState
  }

  //监听路由变化
  routeListen() {
    this.props.history.listen((location) => {
      this.changeTitle(location.pathname)
    })
  }

  //根据路由的变化改变标题栏的标题
  changeTitle(pathname) {
    this.setState({
      visible: true
    })
    switch (pathname) {
      case '/':
      case '/home': document.title = "首页"; break;
      case '/shop': document.title = "购物车"; break;
      case '/mine': document.title = "个人中心"; break;
      // case '/sort':document.title="分类";break;
      default:
        if (pathname.includes("/sort/")) {
          document.title = "分类"
        } else {
          //显示404页面时,隐藏导航
          this.setState({
            visible: false
          })
        }
    }
  }
  render() {
    console.log(this.props)
    return (
      <div className="App">
        <ul className="appContent" style={{ "display": this.state.visible ? '' : 'none' }}>
          <li>
            <NavLink to="/home">
              <span class="iconfont icon-icon"></span>
              <span>首页</span>
            </NavLink>
          </li>
          <li>
            <NavLink to="/sort">
              <span class="iconfont icon-fenlei"></span>
              <span>分类</span>

            </NavLink>
          </li>
          <li>
            <NavLink to="/shop">
              <span class="iconfont icon-shangpingouwudai2"></span>
              <span>购物车</span>

            </NavLink>
          </li>
          <li>
            <NavLink to="/mine">
              <span class="iconfont icon-solid-person"></span>
              <span>个人中心</span>
            </NavLink>
          </li>
        </ul>
        <Switch>
          <Route path="/home" component={Home} />
          <Route path="/sort" component={Sort} />
          <Route path="/shop" component={Shop} />
          <Route path="/mine" component={Mine} />
          <Redirect from="/" to="/home" exact />
          <Route component={NotFound} />
        </Switch>
      </div>
    )
  }
}

export default withRouter(App);

通过上面的代码我么就实现了我们项目的基本路由功能,Router组件决定了我们使用html5 history api,Route组件定义了路由的匹配规则和渲染内容,使用 Link 组件进行路由之间的导航。使用 exact 属性来定义路径是不是精确匹配。

使用url传参数

<Route path='/hello/:name' render={({match}) => {
            return <div>hello {match.params.name}</div>
  }} />

使用 匹配的react 组件会在props 中包含一个match 的属性,通过match.params可以获取到参数对象

调用方法跳转

 <Route path='/hello/:name' render={({ match, history }) => {
          return <div>
            hello {match.params.name}
            <button onClick={()=>{
              history.push('/hello')
            }}>to hello</button>
            </div>
}} />

使用 匹配的react 组件会在props 中包含一个history 的属性,history中的方法

  1. history.push(url) 路由跳转
  2. hisroty.replace(url) 路由跳转不计入历史记录
  3. history.go(n) 根据索引前进或者后退
  4. history.goBack() 后端
  5. history.goForward() 前进

常用组件介绍

BrowserRouter

使用HTML5历史记录API(pushState,replaceState和popstate事件)的,以使您的UI与URL保持同步。

Route

主要职责是当Route的位置和路径匹配的时候渲染对应的ui

属性:

用于渲染的props

1.component
一个react 组件,将在path匹配的时候自动渲染

2.render:func
通过编写一个方法,方法返回一个react dom ,当 path匹配的时候自动渲染

3.children:func
同样是一个方法,匹配规则时无论path是否匹配都会渲染,但是match属性只有在路由匹配的时候才会有值。这样方便你根据路由是否匹配渲染不同的ui

 <Route path='/hello' exact children={({ match, history, location }) => {
          return <div>
            hello {match ? 'match' : ''}
          </div>
        }}></Route>

上面的三种方法都能在组件中获取到route传过去的三个props

history / location / match
其他属性:

4.path:string | string[]
需要匹配的路径或者路径数组

5.exact:bool
如果为true,则仅在路径与location.pathname完全匹配时才匹配。

6.strict
如果为true,则具有尾部斜杠的路径将仅匹配具有尾部斜杠的location.pathname。当location.pathname中有其他URL段时,这不起作用。

7.sensitive:bool
匹配规则对大小写是否敏感,true 的话为区分大小写。

Link

导航到指定的路由

属性:

1.to:string|object
如果值为字符串,则导航到字符串所在的路由
object:

  • pathname :表示链接到的路径的字符串 /hello
  • search :query参数 ?name=cfl
  • hash : hash的值 #weixin
  • state

Switch

呈现于于location.pathname 所匹配的第一个 或。

Prompt
当从当前路由退出的时候给一个提示框。

class TestComp extends React.Component {
  render() {
    return <div>
      <Prompt message='test' when={true}></Prompt>
      test router
    </div>
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值