美文网首页
11-React Router

11-React Router

作者: 谷子多 | 来源:发表于2018-05-17 00:46 被阅读0次

首先在webpack中配置:

 devServer: {
    open: true,
    historyApiFallback: true
  }

这样在每次刷新的时候,都可以渲染到对应的页面,原因 : 访问地址的时候,发现根本找不到这个资源,于是就会去返回 /根路径,路径虽然没有变,路由依然可以起作用,因为它会在这个根的html,然后匹配到根路径里匹配到的路由。


1.引入 :

先安装 : npm install react-router-dom

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

2.

<Router>
      <App></App>
</Router>

概念

React Router 是一个基于 React 之上的强大路由库,它可以让你向应用中快速地添加视图和数据流,同时保持页面与 URL 间的同步。

API:

Link

允许用户浏览应用的主要方式。<Link> 以适当的 href 去渲染一个可访问的锚标签。
<Link> 可以知道哪个 route 的链接是激活状态的,并可以自动为该链接添加 activeClassName 或 activeStyle。

  <li>
    <Link to="/">HOME</Link>
  </li>
  <li>
    <Link to={
      pathname:'/about'
      hash:'hello',
      search:'?a=5&b=9'
      state : 'kkk'
    }>HOME</Link>
  </li>


exact

精确匹配,/a不匹配/

<Route exact path="/" component={Home}></Route>
// 接收 : 在组件内获取this.props即可

path:匹配的路径,一旦匹配上,就渲染相关组件

渲染组件的三种方式:

  1. component:直接给一个组件名(类或函数)
  2. render : 函数,返回要渲染的组件
  3. children : 函数,返回要渲染的组件,和render很像,除了一点:不管path有没有被匹配,children都会被渲染

render prop

如果组件被route匹配到,通过component方式渲染组件,组件内就可以接收到以下三个参数:

history:

React Router 是建立在 history 之上的。 简而言之,一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。

//app.js
<Route exact path="/" component={Home}></Route>
// about.js
export default class extends Component{
  constructor(props){
    super(props)
  }

  componentDidMount(){
    setTimeout(()=>{
      this.props.history.push('./about')
    },4000)
  }
  render(){

    let {history,location,match} = this.props
    console
    return (
      <div>
        <h1>我是HOME</h1>
      </div>
    )
  }
}
location : 位置,描述页面信息

在组件内获取location,并打印

export default class extends Component{
  constructor(props){
    super(props)
  }
  render(){
    let {location} = this.props
    console.log(location)
    return (
      <div>
        <h1>我是HOME</h1>
      </div>
    )
  }
}
屏幕快照 2018-05-17 上午12.23.42.png

图解

// hash : Link标签上,path后的值
<Link to="/about#jijiji">ABOUT</Link>
//search : 查询字符串

为什么不直接histoy.location,而是从props中获取?
因为history是在变化的,比如你一直切换首页,打印location,就会发现这个值是在一直变化的。所以从上一个组件跳转到现在的组件,从histoy.location拿到的是最新的,旧的已经找不到了,所以props获取的location是记录的进入到当前页面那一刻的location,这个值是不变的。

match:当前层级匹配的信息
屏幕快照 2018-05-17 上午12.25.56.png

补充 :
普通组件获取路由信息:

import { withRouter } from 'react-router-dom'
//最后包裹组件
withRouter(AuthRoute)

相关文章

网友评论

      本文标题:11-React Router

      本文链接:https://www.haomeiwen.com/subject/oftvdftx.html