【React Router】React Router API锦囊以及源码(持续更新)

2021/8/6 14:07:04

本文主要是介绍【React Router】React Router API锦囊以及源码(持续更新),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

目录
  • Router 的 类型
  • Router Hooks
    • useParams
    • useRouteMatch
    • useLoaction
    • useSearchParams
    • useHistory
  • withRouter

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


这篇关于【React Router】React Router API锦囊以及源码(持续更新)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程