React routing

Original link: https://www.iyouhun.com/post-229.html

React routing – basic usage

The most widely used v5 version here, v5 documentation , v5 Chinese documentation

NOTE: The v6 version has breaking updates compared to the v5 version! v6 documentation

Steps :

  1. Install: yarn add react-router- [email protected]
  2. Import the three core components of routing: Router / Route / Link
  3. Wrap the entire application with the Router component
  4. Use Link component as navigation menu (routing entry)
  5. Use the Route component to configure routing rules and components to be displayed (routing exits)
 import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const First = () => <p>页面一的页面内容</p> const App = () => { return ( <Router> <div className="App"> <ul> <li> {/* to属性:浏览器地址栏中的pathname(location.pathname) */} <Link to="/first">页面一</Link> </li> </ul> {/* path属性:路由规则component属性:展示的组件Route 组件写在哪,渲染出来的组件就展示在哪*/} <Route path="/first" component={First}></Route> </div> </Router> ) }

React Routing-Router Pattern

  • Router component: wraps the entire application, a React application only needs to be used once

  • Two common routers: HashRouter and BrowserRouter

  • HashRouter: Implemented using the hash value of the URL (

    http://localhost:3000/#/first)

    • Principle: Implemented by listening to the hashchange event of the window
  • (recommend)

    BrowserRouter

    : Implemented using H5’s history.pushState() API (

    http://localhost:3000/first)

    • Principle: Implemented by listening to the popstate event of the window

React Routing – Link&NavLink Components

Link component: used to specify navigation links, which will be rendered as a tag

  • to attribute, which will be rendered as the href attribute of the a tag in the future
 <Link to="/first">页面一</Link> // 渲染为: <a href="/first">页面一</a>

In addition to the Link component, the NavLink component is also provided in the routing library, which can get a highlight class name when the route is matched, so as to specify the highlight effect (the style needs to be manually specified by yourself)

  • It is used in the same way as the Link component, but with an additional highlighting class name

  • activeClassName property: used to specify the highlighted class name, active by default

  • exact attribute: exact match, indicating that it must match exactly (the to attribute value is the same as the pathname in the browser address bar), the class name will take effect

    • By default, when the to attribute of NavLink in React routing is matched, the default is fuzzy matching
    • Fuzzy matching means: as long as the patchname in the browser address bar (for example: /search/a) starts with the value of the NavLink to (/search) attribute, then the match will be successful
 <NavLink to="/first">页面一</NavLink> // 渲染为: <a href="/first" class="active">页面一</a> // --- // Link 的模糊匹配和精确匹配// 模糊匹配: // 浏览器地址栏中的pathname 为:/search/a // 匹配成功的to 属性为: // 1 /search ==> 模糊匹配成功// 2 /search/a ==> 完全相同,匹配成功// 3 /sear ==> 匹配失败,因为/search 是一块完整的内容,必须要出现这一整块内容才可以// 精确匹配: // 浏览器地址栏中的pathname 为:/search/a // 注意:添加exact 属性后,变为精确匹配,此时,这个NavLink 只能匹配/search 这一个patchname 了// React 中如果属性是布尔值可以只写属性名称,不用写后面的= 等内容<NavLink exact to="/search">search 页面</NavLink> // 等价于: <NavLink exact={true} to="/search">search 页面</NavLink>

React routing-Route component

Route component: used to configure routing rules

  • path attribute, specifying routing rules
  • component property, specifying the component to render
  • children child node, specifying the component to render
 // 用法一:使用component 属性指定要渲染的组件<Route path="/search" component={Search} /> // 用法二:使用children 指定要渲染的组件<Route path="/search"> <Search /> </Route>

Note: For Route, if the routing rule matches successfully, the corresponding component will be rendered; otherwise, null or nothing will be rendered.

For Route components, the path property is optional:

  • If the Route component does not have a path attribute, it means that the route will always match successfully and the component will be rendered.
 <Route> <SomeComponent /> </Route>

React routing – route matching pattern

There are two matching modes for routes: 1 fuzzy matching (default), 2 exact matching

fuzzy matching

  • Question: When the value of the to attribute of the Link component is “/login”, why the default route is also matched successfully?
  • React routing is fuzzy matching mode by default
  • Fuzzy matching rule: as long as the pathname (address in the browser address bar) starts with path, the match will be successful
 <Link to="/login">登录页面</Link> <Route path="/" component={Home} /> 匹配成功// pathname 代表Link组件的to属性(也就是location.pathname) // path 代表Route组件的path属性
path Pathname that can be matched (browser address bar)
/ all pathnames
/first /first or /first/a or /first/a/b/…

exact match

  • Question: The default route is displayed in any case, how to avoid this problem?
  • Add the exact attribute to the Route component to make it an exact match mode
  • Exact match: The route will only be shown if the path and pathname match exactly
 // 此时,该组件只能匹配pathname=“/” 这一种情况<Route exact path="/" component=... />

React routing – execution process

When switching pages, the execution process is as follows:

  1. Click the Link component (a tag) to modify the url in the browser address bar
  2. React routing listens to changes in address bar url hashchange popstate
  3. React routing internally traverses all Route components and uses routing rules (path) to match pathname (hash)
  4. When the routing rule (path) can match the pathname (hash) in the address bar, the content of the Route component is displayed

Note: By default, React routing can match multiple successfully at the same time. As long as the matching is successful, the content corresponding to the routing component will be rendered to the page

React Routing – Switch Components & 404 Pages

Switch component: wrapping the Route component, only the first matching component will be rendered , even if there are multiple routes, the matching can be successful

  • In actual development, the Route component is usually wrapped with a Switch component
  • The 404 page function can be implemented very easily through the Switch component:
 <Switch> <Route exact path="/"> <Home /> </Route> <Route path="/about"> <About /> </Route> <Route path="/user"> <User /> </Route> // 即使这个也可以匹配成功/user/a 但是因为Switch 组件的存在,这个路由对应的组件内容是不会渲染的<Route path="/user/a"> <User1 /> </Route> {/* 以上路由规则全都不匹配时,展示404 页面*/} {/* 注意:这个路由需要放在最后,兜底*/} <Route> <NoMatch /> </Route> </Switch>

React Routing – Programmatic Navigation

  • Scenario: Click the login button, after successful login, jump to the background home page through the code, how to achieve this?

  • Programmatic navigation: page jump through JS code

  • The history object provided by the route can be obtained through the useHistory hook, which is used to obtain the relevant information of the browser history. Common operations:

    • push(path) : Jump to a page, the parameter path indicates the path to jump to
    • replace(patch) : Jumping to a page will replace the current history
    • go(n) : go forward or backward to a certain page, the parameter n indicates the number of pages forward or backward (for example: -1 means go back to the previous page)
 import { useHistory } from 'react-router-dom' const Login = () => { const history = useHistory() const onLogin = () => { // ... history.push('/home') } return ( <button onClick={onLogin}>登录</button> ) }

The difference between push(path) and replace(path) jump routes :

The browser will automatically record the visited page path, which can be simply understood as being recorded through an array.

For example: we visited 3 pages: [‘/login’, ‘/home’, ‘/search’], the current page is: ‘/search’

  1. At this time, if we access a new page: ‘/a’ through the push('/a') method, at this time, it is equivalent to pushing a piece of data into the array,
    • Then, after visiting the page, the record in the browser is: [‘/login’, ‘/home’, ‘/search’, ‘/a’]
  2. At this point, if we visit a new page: ‘/a’ through the replace('/a') method, at this time, it is equivalent to replacing the current page address with ‘/a’
    • Then, after visiting the page, the record in the browser is: [‘/login’, ‘/home’, ‘/a’]

This article is reprinted from: https://www.iyouhun.com/post-229.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment

Your email address will not be published.