1. Install dependencies
npm i react-router-dom
Copy the code
  1. Introduces the components needed to implement the routing, as well as the page components
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Foo from './Foo';
import Bar from './Bar';
​
function App(){
    return (
        <BrowserRouter>
            <Routes>
                <Route path='/foo' element={Foo} />
                <Route path='/bar' element={Bar} />
            </Routes>
        </BrowserRouter>)}Copy the code

Note: The BrowserRouter component is best placed outside of all components at the top level to ensure that internal components do not fail when routing links

A,SwitchrenameRoutes(Used as above)

Second,Routing hop

When redirecting a route, if the path starts with /, it is an absolute route; otherwise, it is a relative route, that is, the route is changed relative to the current URL

Three,Link component

A Link component can only be used within a Router, so components that use a Link component must be placed within the top-level Router

import { Link } from 'react-router-dom';
​
<Link to='foo'>to foo</Link>
Copy the code

Four,NavLink components

  • NavLink componentsandLink componentThe difference is that it can be judgedTo attributeWhether it is the currently matched route
  • NavLink componentsthestyleorclassNameYou can take one function, and the function takes oneIsActive parameters, you can adjust the style according to this parameter
import { NavLink } from 'react-router-dom';
​
function Foo(){
    return (
        <NavLink
            style={ (isActive) = > ({color: isActive ? 'red' : '#fff'}) }
        >Click here</NavLink>)}Copy the code

Five,Outlet (Render any matching sub-routing page)

      return (
        <div className="A">
          <h3>I am A component --------- programmatic route navigation use example</h3>
          <div className="A-navBox">
            <Button type="primary" onClick={()= >NavigateRouter (1, 1, "I am Jason Ma")}</Button>
            <Button onClick={()= >NavigateRouter (2, 18, "I am Jason Ma")}>search</Button>
            <Button type="dashed" onClick={()= >NavigateRouter (3, 999, "I am Jason Ma")}> state</Button>
          </div>{/* Render any matching sub-routing page */}<Outlet></Outlet>
        </div>
  );
Copy the code

Vi.Gets the params parameter

  • inThe Route componentIn thePath propertiesDefines path parameters in
  • Passes within the componentuseParamsHook Access path parameters
<BrowserRouter>
    <Routes>
        <Route path='/foo/:id' element={Foo} />
    </Routes>
</BrowserRouter>
​
import { useParams } from 'react-router-dom';
export default function Foo(){
    const params = useParams();
    return (
        <div>
            <h1>{params.id}</h1>
        </div>)}Copy the code

In previous versions, the component’s props would contain a match object from which path parameters could be fetched. However, in the latest 6.x version, parameters cannot be obtained from props.

Also, the withRouter higher-order component for the class component has been removed. So there are two compatible ways to use parameters for class components:

  1. Rewrite a class component into a function component
  2. Bytes write a HOC to wrap the class component, use useParams to get the argument and pass in the original class component via props

Seven,Programmatic routing navigationwithuseNavigateInstead ofuseHistory

Navigate objects are generated using the useNavigate hook function, which can be used to navigate through the JS code

// v5
import { useHistory } from 'react-router-dom';
 
 
function MyButton() {
  let history = useHistory();
  function handleClick() {
    history.push('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};
Copy the code

Now, history.push() will be replaced with navigation() :

// v6
import { useNavigate } from 'react-router-dom';
 
 
function MyButton() {
  let navigate = useNavigate();
  function handleClick() {
    navigate('/home');
  };
  return <button onClick={handleClick}>Submit</button>;
};
Copy the code

The use of history will also be replaced with:

// v5
history.push('/home');
history.replace('/home');
 
 
// v6
navigate('/home');
navigate('/home', {replace: true});
Copy the code

Eight,The search parameters

  • Query parameters do not need to be defined in the route
  • useuseSearchParamsHook to access query parameters. Its usage is similar to useState in that it returns the current object and methods to change it
  • When you change the searchParams, you must pass in all query parameters, otherwise existing parameters will be overwritten
import { useSearchParams } from 'react-router-dom'; // The current path is /foo? id=12 function Foo(){ const [searchParams, setSearchParams] = useSearchParams(); console.log(searchParams.get('id')) // 12 setSearchParams({ name: 'foo' }) // /foo? name=foo return ( <div>foo</div> ) }Copy the code

Nine,The default route

Definition: In nested routines, if the URL matches only the parent URL, the Outlet displays the route with the index attribute

<Routes>
    <Route path='/foo' element={Foo}>
        <Route index element={Default}></Route>
        <Route path='bar' element={Bar}></Route>
    </Route>
</Routes>
Copy the code
  • When the URL is /foo: Outlets in foo show the Default component
  • When the URL is /foo/bar: Outlets in foo are displayed as bar components

Ten,Fully matched routing

Definition: When the path attribute is *, any (non-empty) path can be matched, and the match has the lowest priority. Can be used to set up 404 pages.

<Routes>
    <Route path='/foo' element={Foo}>
        <Route path='bar' element={Bar}></Route>
        <Route path='*' element={NotFound}></Route>
    </Route>
</Routes>
Copy the code

Eleven,Multiple sets of routing

Typically, there is only one Routes component in an application.

However, you can define multiple exit routes as required (for example, both the sidebar and the main page vary with the URL)

<Router>
    <SideBar>
        <Routes>
            <Route></Route>
        </Routes>
    </SideBar>
    <Main>
        <Routes>
            <Route></Route>
        </Routes>
    </Main>
</Router>
Copy the code

Twelve,redirect

When you need to redirect to a path/B from a path/A, you can redirect to another path via the Navigate component

Equivalent to the Redirect component in previous versions

import { Navigate } from 'react-router-dom';
function A(){
    return (
        <Navigate to="/b" />
    )
}
Copy the code

Brothers and sisters, click on the wave to share fun technology!

The Denver nuggets:Juejin. Cn/user / 303430…All original good articles

CSDN:Blog.csdn.net/qq_42753705…All original good articles

Segmentfault think no:Segmentfault.com/u/jasonma19…All original good articles