react-router

61 阅读1分钟

react-router在hooks中的使用

useHistory

    import { useHistory } from 'react-router-dom'
    const history = useHistory()
    history.push('/home')

useLocation

    import {  
      BrowserRouter as Router,
      useHistory,
      Switch,
      useLocation
    } from 'react-router-dom'
    import reactDom from 'react-dom'

    // 监听url的改变
    const usePageViews = () => {
      let location = useLocation()
      useEffect(() => {
        console.log('pathname', location.pathname)
      }, [location])
    }
    const App = () => {
      usePageViews()
      return <Switch></Switch>
    }
    reactDom.render( 
      <Router>
        <App/>
      </Router>
      , node)

useParams

获取当前路由的参数,返回一个对象URL参数的键值对

    import ReactDOM from "react-dom";
    import {
      BrowserRouter as Router,
      Switch,
      Route,
      useParams
    } from "react-router-dom";

    const BlogPost = () => {
      const { slug } = useParams();
      return <div>Now showing post { slug }</div>
    }

    ReactDOM.render(
      <Router>
        <Switch>
          <Route exact path="/">
            <HomePage />
          </Route>
          // 动态路由参数
          <Route path="/blog/:slug">
            <BlogPost/>
          </Route>
        </Switch>
      </Router>
      , node
    )

useRouteMatch

useRouteMatch尝试与Route相同的方式匹配当前url,主要用于访问匹配数据,而无需实际渲染Route

 import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useRouteMatch,
} from "react-router-dom";

const App = () => {
  return <Router>
    <Switch>
      <Route exact path="/" component={Home}></Route>
      <Route path="/profile" component={Profile}></Route>
    </Switch>
  </Router>
}
const Profile = () => {
  let match = useRouteMatch();
  return (
    <div>
      <Nav>
        <Link to={`${match.url}/me`}>My profile</Link>
      </Nav>
      <Switch>
        <Route path={`${match.path}/me`}>
          <MyProfile />
        </Route>
        <Route path={`${match.path}/:id`}>
          <OtherProfile />
        </Route>
      </Switch>
    </div>
  )
}
    // 在v6版本中省去了 useRouteMatch 这一步,支持直接用 path 表示相对路径:
    import { BrowserRouter, Routes, Route, Link, Outlet } from "react-router-dom";
    const App = () => {
      return (
        <BrowserRouter>
         <Routes>
           <Route path="/" element={<Home />}/>
           <Route path="profile" element={< Profile/>}>
            <Route path="me" element={<MyProfile />}/>
            <Route path=":id" element={<OtherProfile/>}/>
           </Route>
         </Routes>
        </BrowserRouter>
      )
    }

    const Profile = () => {
      return <div>
        <Nav>
          <Link to="me">My Profile</Link>
        </Nav>
        {/* 渲染子路由的元素 */}
        <Outlet/>
      </div>
    }

Link

    <Link to="/courses?sort=name"></Link>
    <Link to={{
      pathname: '/courses',
      search: '?sort=name',
      state: { fromDashboard: true }
    }}></Link>
    <Link to={location => ({
      ...location,
      pathname: '/courses'
    })}></Link>
    <Link to={location => `${location.pathname}?sort=name`}></Link>
    // 点击链接进入历史堆栈 而不是创建一个新的
    <Link to="/courses" replace></Link>

Route的render-props

 // render-props
    <Router>
      <FadingRoute path="/cool" component={Something}></FadingRoute>
    </Router>

    const FadingRoute = ({ component: Component, ...rest }) => {
      return (
        <Route 
         { ...rest }
         render={routeProps => (
           <FadeIn>
             <Component { ...routeProps }/>  
           </FadeIn> 
         )}
        />