react-router 入门笔记

2019-07-29  本文已影响0人  copyLeft

React-router 笔记 官方文档

基本思路

基础标签

基本使用

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

// component
import Btn from'./btn'

// pages

function home(props){

    return (
        <div className="home">
            home
        </div>
    )

}

function products(props){
    return (
        <div className="products">
            products
        </div>
    )
}

function about(props){
    return(
        <div className="about">
            about
        </div>
    )
}

function product(props){
   return (

    <div>
        product
    </div>

   )
}

// router-config

const routerConfig = [

    {
        label: 'home',
        path:'/',
        component: home,
        exact: true,

    },
    {
        label: 'products',
        path: '/products',
        component: products,
        exact: true,
    },
    {
        label: 'about',
        path: '/about',
        component: about
    },
    { 
        label: 'procut',
        path: '/products/:id',
        component: product
    }

]

// container

export default class pages extends Component{

    render(){

        const buildLabel = () =>{

            let tempalte = [];

            for(let item of routerConfig){
                tempalte.push(

                    <Btn key={item.label}>
                        <Link to={item.path}>
                            {item.label}
                        </Link>
                    </Btn>
                )
            }
            return tempalte
        }

        return (
            <Router>
                <div className='pages-container'>

                    <div className="tab">
                    {buildLabel()}
                    </div>

                    {
                        routerConfig.map((item) =>{
                            return (
                                <Route exact={item.exact} key={item.label} path={item.path} component={item.component}/>
                            )
                        })
                    }

                </div>

            </Router>
        )

    }

}

路由传参


// pages
function home(props){

    return (
        <div className="home">
            in home page
            <br/>
            router parmas: 
            <br/>
            { props.match.params.userId }
        </div>
    )

}

render(){

    return (
        <Router>
            <div className='pages-container'>

                <Link to='/userId'>
                    to user page
                </Link>

                <Route exact path='/' component={home}></Route>
                <Route path='/:userId' component={home}></Route>

            </div>
        </Router>
    )

}

重定向 Redirect

通过返回组件 Redirect 实现重定向

 function subPage(props){

    return (
        <Redirect to={{
            pathname: '/in_show_page'
        }}></Redirect>
    )

 }

return (
    <Router>
        <div className='pages-container'>

            <Link to='/subPage'>
                to sub page
            </Link>

            {/* 参数路由 */}
            <Route path='/:userId' component={home}></Route>

            {/* 重定向路由 */}
            <Route path='/subPage' component={subPage}></Route>

        </div>
    </Router>
)

命令式导航(history)

withRouter

// 使用 withRouter 处理组件,组件props中将包含 路由相关对象, { match, location, history }

// 定义组件
function jump (props){

    const { match, location, history } = props;
    console.log(props)

    return (

        <div>

            <button onClick={ history.goBack }> back </button>
            <button onClick={ () =>{history.push('/home')} }> jump to home </button>
            <button onClick={ () =>{ history.replace('/subPage') } }> replace path </button>

        </div>

    )

}

// 在父组件中构件

  render(){

    return (
        <Router>
        <div className="route-render">

            <Link to='/history'> history </Link>

            <Route path='/history' component={withRouter(jump)} ></Route>

        </div>
        </Router>
    )

}

跳转拦截 (Prompt)


//跳转提示, 每次路由跳转,提示信息 
<Prompt message="路由将跳转"/>

//message 为函数
<prompt message={ lcoation => (`跳转地址 ${location.pathname}`) } />

// 带触发条件 when = Boolean
<Propmt when={ location.pathname === '/home' } message='你将进入home页面' />

// 

标签API

<Router>

<Route>

<Switch>


     /**
     * 路径为 '/' 只会渲染 home 组件
     */

    <Switch>

        <Route path='/' componet={home}/>
        <Route path='/about' componet={about}/>
        <Route path='/product' componet={product}/>

    </Switch>

路由参数

路由嵌套


 //父组件
 <App>
    <BrowserRouter>
        <div>
            <Route path='/' component={Home} />           
             <Route path='/about' component={About} /> 

            <Sub/>
        </div>
    </BrowserRouter>
 </App>

 //子组件

<div className='sub'>
    <Link to='/about'> to about </Link>

    <Route path='/about'  rennder={ () =>( <div> in sub about </div> ) } />
</div>

/**
 * Sub中的路由组件 与App中的路由组件处于同一层级, 当点击 Link标签时, 将进入 About 而不是Sub的自定义组件
 */


//父路由

let AppRouter = [

  {
    label: 'home',
    path: '/',
    component: Home,
    exact: true
  },
  {
    label: 'user-center',
    path: 'user-center',
    component: UserCenter
  },
  {
    label: 'books',
    path: '/books',
    component: Books
  },
  {
    label: 'book',
    path: '/books:id',
    component: Books
  }

]

return (
      <Router>
        <div className="App">

            <Switch>
                {routes}
            </Switch>

        </div>
      </Router>
    );

//子路由

  <Router>
   <div>
        <h4>路由</h4>
        <Link to='/books'>  to sub </Link>

        <Route path='/' render={ () =>( <div> 路由嵌套 path='/' </div> ) }></Route>
        <Route path='/books' render={ () =>( <div> 路由嵌套 path='/sub' </div> ) }></Route>
   </div>
</Router>

 /*
 ** 这是个路由冲突的例子, 可以看到,在父组件和子组件中,都配置了路径 '/books', 
 ** 当触发 Link 跳转时,将显示自组件内的组件, 即显示: '路由嵌套,path=/sub'
 ** 看起来一切正常,但当我们刷新页面, 将进入主路由的 Books 组件, 所以对于这样的路由冲突,编写时不易发现
 */

component, rander, children 的区别

自定义history


import { Router} from 'react-router-dom'
import { createBrowserHistory } from 'history'

// 创建history
const history = createBrowserHistory()

// 包装原方法, 添加日志功能
const go = history.go
history.go = n => {
    console.log(`go to --> ${n}`)
    go(n)
}

// 监听路由变化, 重定向
history.listen(( location, action ) => {

    const isLogin = false
    if( isLogin ) {
        setTimeout(() => {
            history.push("/login")
        })
    }

})

上一篇下一篇

猜你喜欢

热点阅读