current position:Home>[react] react routing concept

[react] react routing concept

2022-04-29 14:35:53Nanzhi ~zmt


1. Routing Overview

route :

Simply speaking , Routing is based on different url Address shows different content or pages .

  1. A route is a mapping relationship (key:value)
  2. key Is the path ,value May be function perhaps component

And the concept of routing first appeared on the back end , Because the early web pages were rendered by the server , such as :JSP,PHP,ASP Other languages , Are directly returned to the rendered html Show the client .


1.1 Back end routing

stay web In the early days of development , The function of the front end is far less powerful than now , Back end routing has always been the dominant address .

Whether it's jsp, still php、asp, Users can go through URL Visit the page , Most of them are returned to the browser through back-end route matching .

user-requested url Navigate to specific html page ; Every jump to a different URL, It's all about revisiting the server , Then the server returns to the page , The page can also be a server to obtain data , Then combine with the template , return HTML; You can also directly return to the template HTML, And then by the front end js Then ask for data , Use front-end templates and data to combine , Generate the desired HTML.

On the back end , The routing mapping table is different URL The address is different from html + css + Back end data Mapping between .
 Insert picture description here

  • understand :value yes function, Used to process requests submitted by clients .
  • Registered routing :router.get(path,function(req,res));
  • working process : When the server receives a request , Find a matching route according to the request path , Call the function in the route to process the request , Return response data .

1.2 Front-end routing

Front end routing was later developed to SPA( A single page application ) The concept that emerged when .

  • Front end routing gives the task of different content or pages corresponding to different routes to the front end .
  • Browser side routing ,value yes component, Used to display page content .
  • Registered routing :<Route path="/test" component={Test}>
  • working process : As a browser path Turn into /test when , The current routing component will become Test Components

Advantages of front-end routing :

  1. In terms of performance and user experience , The back-end route sends a request to the server every time it visits a new page , Then the server responds to the request , There must be a delay in this process . The front-end route only changes the path when visiting a new page , No network latency , It will greatly improve the user experience .
  2. In some cases , use ajax request , Can make the page without refresh , The page has changed, but url There is no change , Users can't copy to the desired address , Using front-end routing as a single page web page solves this problem .

Disadvantages of front-end routing :
Using the browser forward , When the back key is pressed, the request will be sent again , Not using cache properly .


2. SPA

  • Single page web application SPA(single page web
    application), It's a single page application , It is the most common front-end development at present , The whole website consists of one html Page composition .
  • The three framework Angular Vue React All are SPA.
  • The whole application has only one complete page .
  • Clicking the link in the page will not refresh the page , Only do partial updates to the page .
  • All data needs to pass through ajax The request for , And show it asynchronously on the front end .

3. There are two modes of front-end routing

From the perspective of users , Front end routing mainly realizes two functions ( Use ajax Update page status ):

  • Record the status of the current page ( Save or share the of the current page url, Open the... Again url when , The web page is still the state when it is saved or shared ).
  • You can use the browser's forward and backward function ( If you click the back button , You can return the page to use ajax Update the status before the page ,url Also return to the previous state )

As a developer , Realize these two functions , It needs to be done :

  • change url And don't let the browser send requests to the server
  • testing url The change of
  • to intercept url Address , And analyze the required information to match the routing rules

3.1 hash Pattern

there hash Is refers to url Behind the tail # The number and the following characters . there # and css Inside # It means the same thing .
hash Also known as Anchor point , Itself is used to do Page positioning Of , Can make the corresponding id The elements of are displayed in the visual area .

because hash A change in value does not cause the browser to make a request to the server , So it doesn't refresh the page , So as to achieve the effect of no refresh .
So in html5 Of history Before it appeared , It's basically using hash To implement front-end routing .

hash attribute : In the current page , Can pass :window.location.hash = 'edit' To change the current url Of hash value , Carry out the above hash assignment , Page url Change .
for example : Before assignment :http://localhost:3000 After the assignment :http://localhost:3000 /#edit.

hashchange event : hash Change will trigger hashchange event , It can also be controlled by the forward and backward of the browser . With monitoring events , And change hash The page does not refresh , In this way, the callback function that listens for events can , Perform our show and hide different UI The function of display , So as to realize the front-end routing .

window.addEventListener('hashchange', function(){
    
    //  monitor hash change , Clicking forward or backward will trigger 
})

Besides , To change the page hash value , You can also use html Of <a> label To achieve page Jump :<a href="#edit"></a>

hash The shortcomings of :

  • Search engine pair with hash Your page is not friendly
  • with hash It's hard to track user behavior on your page

3.2 history Pattern

Already there. hash The model , and hash Compatible to IE8,history Only compatible to IE10, Why do we still need history Well ?

reason :

  1. hash Itself is used for page positioning , If used for routing , The original anchor function cannot be used .
  2. hash The parameters are based on url Of , If you need to transfer complex data , There will be volume limitations ; and history Patterns can be used not only in url Put parameters in , You can also store data in a specific object .

history Properties of :

  • length: Returns the number of records in the session history , Contains the current session page . If you open a new tab, So this length Will add 1
  • state: Save the popState Wait for the event method , The properties and objects passed ( It'll be later pushState and replaceState The method is described in detail )

history Methods :

  • history.back(): Return to the previous page in the browser session history , With the browser Back off The buttons function the same
  • history.forword(): Point to the next page in the browser session history , With the browser Forward Button is the same.
  • history.go(n): You can jump to... In the browser session history A specified record page ,n Can be positive or negative
  • history.pushState(state, title, url):pushState Sure Push the given data into the browser session history stack , This method accepts 3 Parameters , object ,title, And a bunch of url, It is worth noting that ,pushState After calling, the page will be changed url, But it doesn't refresh the page
    • state: Data to be saved , This data is triggering popstate When an event is , Can be in event.state get
    • title: title , Basically useless , General biography null
    • url: Set a new history of url. new url With the current url Of origin It must be the same , Otherwise, an error will be thrown .url It could be an absolute path , It could be a relative path .
    • for example : At present url yes https://www.baidu.com/a/, perform history.pushState(null, null, ‘./qq/’), Has become a https://www.baidu.com/a/qq/, perform history.pushState(null, null, ‘/qq/’), Has become a https://www.baidu.com/qq/
  • history.replaceState(state, title, url):replaceState The of the current session page url Replace with the specified data ,replaceState It will also change the of the current page url, But it won't refresh the page .

history The advantages of :

  • Friendly to search engines
  • Facilitate the statistics of user behavior

history The shortcomings of :

  • Compatibility is not as good as hash
  • The backend needs to be configured accordingly , Otherwise, when you visit the sub page, you will see 404 error .

copyright notice
author[Nanzhi ~zmt],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291256214695.html

Random recommended