1. 程式人生 > 其它 >【React Router】React Router API錦囊以及原始碼(持續更新)

【React Router】React Router API錦囊以及原始碼(持續更新)

目錄

Router 的 型別

BrowserRouter, HashRouter: https://reactrouter.com/web/example/basic

Router Hooks

useParams

作用:獲取路由中的引數, 比如獲取id等等
地址:https://reactrouter.com/web/api/Hooks/useparams

useRouteMatch

作用:從父路由中繼續渲染子路由
地址:https://reactrouter.com/web/api/Hooks/useroutematch

useLoaction

作用:返回location裡面的一些資訊,比如pathname, search等等
連結:https://reactrouter.com/web/example/no-match

useSearchParams

作用:獲取search的引數
連結:https://reactrouter.com/web/example/query-parameters

useHistory

作用:比如需要push一個路由進去等等
連結:https://reactrouter.com/web/api/Hooks/usehistory

withRouter

作用:不是通過路由切換過來的元件中,將react-router 的 history、location、match 三個物件傳入props物件上
連結:

https://reactrouter.com/web/api/withRouter
demo:

import React,{Component} from 'react'
import {Switch,Route,NavLink,Redirect,withRouter} from 'react-router-dom' //引入withRouter
import One from './One'
import NotFound from './NotFound'
class App extends Component{
    //此時才能獲取this.props,包含(history, match, location)三個物件
    console.log(this.props);  //輸出{match: {…}, location: {…}, history: {…}, 等}
    render(){return (<div className='app'>
            <NavLink to='/one/users'>使用者列表</NavLink>
            <NavLink to='/one/companies'>公司列表</NavLink>
            <Switch>
                <Route path='/one/:type?' component={One} />
                <Redirect from='/' to='/one' exact />
                <Route component={NotFound} />
            </Switch>
        </div>)
    }
}
export default withRouter(App);  //這裡要執行一下WithRouter