Updates in React Router v6

Update in header react-router v6

React Router is a powerful routing library based on React that allows you to quickly add views and data flows to your application while keeping pages and URLs in sync

import { BrowserRouter as Router, Routes, Route, Outlet } from 'react-router-dom';

1. Switch renamed to Routes

​ Routes is an upgraded version of the previous Switch component, which includes functions such as relative routing and links, automatic routing ranking, nested routing and layout

2. New features of Route

​ Responsible for rendering the UI of the React component. The path attribute in it always matches the current url. The second required attribute is called element. When it encounters the current url, it will tell the Route component which React component to render. The element here is v6 Newly added, replace the attribute of the component in v5

import Children from './Children';
// v5
<Route path=":id" component={Children} />
<Route
  path=":id"
  render={routeProps => (
    <Profile routeProps={routeProps} />
  )}
/>
// v6
<Route path=":userId" element={<Profile />} />

3. Routing nesting is simpler, new API: Outlet

​ This is very important. When routing is nested, it is generally believed that a certain part of the web page remains unchanged, and only sub-parts of the web page change

​ In v5, nested routes must be clearly defined, which is not the case in v6. He picks an optimal element named Outlet from the React Router library, and renders any matching child elements for a specific route

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="new" element={<New/>}>
          <Route path=":id" element={<List/>} />
          <Route path="me" element={<Others/>} />
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

function New() {
  return (
    <div>
      <nav>
        <Link to="me">My Profile</Link>
      </nav>
        {/*
       将直接根据上面定义的不同路由参数,渲染<MyProfile />或<OthersProfile />
        */}
      <Outlet/>
    </div>
  )
}

4.useNavigate

​ useNavigate replaces useHistory, useNavigate does not save the routing information in useHistory, and obtain routing information through useLocation

// v5
history.push('/new')
history.replace('/new')
history.go(-1)

// v6
navigate('/new')
navigate('/new', {replace: true})
navigate(-1)

5.useRoutes

function App() {
  let element = useRoutes([
    { path: '/', element: <Home /> },
    { path: 'dashboard', element: <Dashboard /> },
    { path: 'invoices',
      element: <List />,
      children: [
        { path: ':id', element: <List /> },
        { path: 'new', element: <New /> }
      ]
    },
    // 重定向
    { path: 'home', redirectTo: '/' },
    // 404找不到
    { path: '*', element: <NotFound /> }
  ]);
  return element;
}

6. All path matching in v6 ignores the '/' at the end of the URL, and strict in Route has been deleted in v6

// v5 之前存在的路由歧义
1.当前路径'/users',则<Link to='me'>将跳转<a href='/me'>
2.当前路径'/users/',则<Link to='me'>将跳转<a href='/users/me'>

// v6修复了这种歧义
1.当前路径'/users',则<Link to='me'>将跳转<a href='/users/me'>
2.当前路径'/users',则<Link to='../me'>将跳转<a href='/me'>

// 像命令行中cd的用法
当前路径为 /app/dashboard
<Link to='stats'>			// <a href='/app/dashboard/stats'>
<Link to='../stats'>		// <a href='/dashboard/stats'>
<Link to='../stats'>		// <a href='/stats'>
<Link to='../../../stats'>		// <a href='/stats'>

7. Retain useParams and useLocation in v5

8. There is no withRouter in v6, but it will be used in many cases in class components

const withRouter = Component => {
  const ComponentWithRouterProp = props => {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return (
      <Component
        {...props}
        router={
   
   {location, navigate, params}}
      />
    );
  };

  return ComponentWithRouterProp;
};

9. Size, reduced from 20.5KB to 7.4KB

Guess you like

Origin blog.csdn.net/qq_37440870/article/details/126635460