React 路由

547 阅读3分钟

这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战

根据不同的路径,显示不同的组件(内容):react使用的库 => react-router-dom

安装: cnpm install react-router-dom --save

ReactRouter三大组件:

  • Router:所有路由组件的根组件(底层组件),包裹路由规则的最外层容器
  • Route: 路由规则匹配组件, 显示当前规则对应的组件
  • Link:路由跳转组件
  • Redirect: 路由重定向
  • replace: 前进后无法后退,常用于登录后
  • push: 页面栈+1
  • Switch:当路由中有一样的路径,就会默认只显示第一个
  • switch:
import react from 'react'
import { BrowserRouter as Router, Link, Route, Redirect, Switch } from 'react-router-dom'
class App extends react.Component {
  render() {
    return (
      <div>
        <Router>
          <Switch>
            <Route path="/" exact component={() => (<h1>首页</h1>) }></Route>
            <Route path="/form" exact component={ FormCom }></Route>
            <Route path="/login" exact component={() => (<h1>登录</h1>) }></Route>
            <Route path="/loginInfo" exact component={ LoginInfo }></Route>
            <Route path="/abc" exact component={() => (<h1>123</h1>)}></Route>
            <Route path="/abc" exact component={() => (<h1>1234</h1>)}></Route>
          </Switch>
        </Router>
      </div>
    )
  }
}

localhost:3000/abc   =>		只显示123

注意:如果要精确匹配,那么可以在route上设置exact属性

import React from 'react'
import ReactDom from 'react-dom'

// hash模式
// import { HashRouter as Router, Link, Route } from 'react-router-dom'

// history模式 / 后端配合使用
import { BrowserRouter as Router, Link, Route } from 'react-router-dom'

function Home() {
  return (
    <div>
      <h1>首页</h1>
    </div>
  )
}

function Product() {
  return (
    <div>
      <h1>产品页面</h1>
    </div>
  )
}

function Me() {
  return (
    <div>
      <h1>我的</h1>
    </div>
  )
}

// Router:所有路由组件的根组件(底层组件),包裹路由规则的最外层容器
// Route: 路由规则匹配组件, 显示当前规则对应的组件
// Link:路由跳转组件
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  render() {
    return (
      <div id="app">
        <div>所有页面普通内容</div>
        <Router basename="/">  {/* basename 就是在路径前加一个前缀 */}
          <div className="nav">
            <Link to="/">Home</Link>
            <Link to="/product">Product</Link>
            <Link to="/me">个人中心</Link>
          </div>
          <Route path="/" exact component={ Home }></Route>
          <Route path="/product" component={ Product }></Route>
          <Route path="/me" component={ Me }></Route>
        </Router>
      </div>
    )
  }
}

ReactDom.render(<App />, document.getElementById('root'))

link组件可以设置to属性来进行页面的跳转, to属性可以直接写路径给字符串, 也可以通过一个对象, 进行路径的设置

如:

import React from 'react'
import ReactDom from 'react-dom'

// hash模式
// import { HashRouter as Router, Link, Route } from 'react-router-dom'

// history模式 / 后端配合使用
import { BrowserRouter as Router, Link, Route } from 'react-router-dom'

function Home() {
  return (
    <div>
      <h1>首页</h1>
    </div>
  )
}

function Product() {
  return (
    <div>
      <h1>产品页面</h1>
    </div>
  )
}

function Me(props) {
  console.log(props)
  return (
    <div>
      <h1>我的</h1>
    </div>
  )
}

// Router:所有路由组件的根组件(底层组件),包裹路由规则的最外层容器
// Route: 路由规则匹配组件, 显示当前规则对应的组件
// Link:路由跳转组件
class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  render() {
    const meObj = {
      pathname: "/me",  // 跳转的路径
      search: '?username=admin',   // get请求数据
      hash: '#abc',   // 设置的hash值
      state: { msg: 'hello world' } // 传入组件的数据
    }  // 路径拼接
    return (
      <div id="app">
        <div>所有页面普通内容</div>
        <Router basename="/">  {/* basename 就是在路径前加一个前缀 */}
          <div className="nav">
            <Link to="/">Home</Link>
            <Link to="/product">Product</Link>
            <Link to={ meObj }>个人中心</Link>
						{/* replace 删除页面栈,无法后退 */}
            <Link to={ meObj } replace>个人中心</Link>
          </div>
          <Route path="/" exact component={ Home }></Route>
          <Route path="/product" component={ Product }></Route>
          <Route path="/me" component={ Me }></Route>
        </Router>
      </div>
    )
  }
}

ReactDom.render(<App />, document.getElementById('root'))

link的replace属性:点击链接后, 将新地址替换成历史访问记录的原地址

动态路由实现

重定向组件: 如果访问某个组件时, 如果有重定向组件, 那么就会修改页面路径,使得页面显示为所定向路径的内容

import React from 'react'
import { BrowserRouter as Router, Route, Link, Redirect } from 'react-router-dom'

function LoginInfo(props) {
  console.log(props)
  if(props.location.state.loginState === 'success') return <Redirect to="/admin"></Redirect>
  else return <Redirect to="login"></Redirect>
}

const FormCom = () => {
  const pathObj = {
    pathname: '/loginInfo',
    state: {
      loginState: 'success'
    }
  }
  return (
    <div>
      <h1>表单验证</h1>
      <Link to={ pathObj }>登录验证后页面</Link>
    </div>
  )
}

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }
  render() {
    return (
      <div>
        <Router>
          <Route path="/" exact component={ () => (<h1>首页</h1>) }></Route>
          <Route path="/form" exact component={ FormCom }></Route>
          <Route path="/login" exact component={ () => (<h1>登录页</h1>) }></Route>
          <Route path="/loginInfo" exact component={ LoginInfo }></Route>
        </Router>
      </div>
    )
  }
}

export default App

最后

公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西

有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭

注释都写到代码里面了,望见谅