In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how to achieve react-router, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
First, the basis of react-router dependency-history
1. The overall introduction of History
For history, it is an independent third-party js library that is compatible with the management of history records in different environments and browsers. It also has a unified API, which is mainly divided into these categories in history:
History of the old browser: mainly realized through hash, corresponding to createHashHistory.
High-version browser: through the history in html5, corresponding to createBrowserHistory.
Node environment: mainly stored in memeory, corresponding to createMemoryHistory.
For these three classes, three more PAI are provided in different environments, and they have some operations of the same nature, which is to abstract the public file createHistory, as shown in the following code:
/ / Internal abstract implementation function createHistory (options= {}) {... Return {listenBefore, / / internal hook mechanism, which can perform certain behaviors before the location changes. The implementation of AOP listen, / / location triggers the callback transitionTo when the change occurs, / / executes the change push of location, / / changes location replace, go, goBack, goForward, createKey, / / creates the key of location, which is used to uniquely identify the location. Is randomly generated createPath, createHref, createLocation, / / create location}}
The most basic internal methods of history mentioned above are: createHashHistory, createBrowserHistory, createMemoryHistory, they only cover some of these methods. It is worth noting that the location at this time is different from the native location of the browser. However, the biggest difference is that there are more key fields in the history, and the location operation is performed inside the history through key. The code is as follows:
Function createLocation () {return {pathname, / / url basic path search, / / query field hash, / / url hash value state, / / url corresponding state field action, / / divided into push, replace, pop three key / / generation methods are: Math.random (). ToString (36) .substr (2, length)}}
2. Internal analysis
The implementation of the three API we mentioned is as follows:
CreateBrowserHistory: take advantage of the history in HTML5.
CreateHashHistory: hash is used to store history information in different states.
CreateMemoryHistory: the storage of history records in memory.
3. Execute URL forward
The way these three methods execute URL is as follows:
CreateBrowserHistory: pushState 、 replaceState .
CreateHashHistory: location.hash=*** location.replace ().
CreateMemoryHistory: the storage of history records in memory.
The implementation of the pseudocode is as follows:
/ / forward implementation in createBrowserHistory (HTML5) function finishTransition (location) {... Const historyState = {key};... If (location.action = = 'PUSH')) {window.history.pushState (historyState, null, path);} else {window.history.replaceState (historyState, null, path)}} / / createHashHistory's internal implementation function finishTransition (location) {... If (location.action = = 'PUSH') {_ window.location.hash = path;} else {_ window.location.replace (_ window.location.pathname + _ window.location.search +' #'+ path);} / / the internal implementation of createMemoryHistory entries = []; function finishTransition (location) {. Switch (location.action) {case 'PUSH': entries.push (location); break; case' REPLACE': entries [current] = location; break;}}
4. Detect URL fallback
The three methods are used as follows:
CreateBrowserHistory: popstate .
CreateHashHistory: hashchange .
CreateMemoryHistory: because it operates in memory, has nothing to do with the browser, and does not involve things at the UI level, you can directly roll back the historical information.
The pseudocode is implemented as follows:
/ / backward detection in createBrowserHistory (HTML5) function startPopStateListener ({transitionTo}) {function popStateListener (event) {... TransitionTo (getCurrentLocation (event.state));} addEventListener (window, 'popstate', popStateListener);...} / / createHashHistory backward detection function startPopStateListener ({transitionTo}) {function hashChangeListener (event) {... TransitionTo (getCurrentLocation (event.state));} addEventListener (window, 'hashchange', hashChangeListener);.} / / the internal implementation of function go (n) {if (n) {. Current + = n; const currentLocation = getCurrentLocation (); / / change action to POP history.transitionTo ({... currentLocation, action: POP});}}
5. Storage of state
For state storage, when we are trying to maintain its state, we store it in our sessionStorage, as follows:
/ / Storage function saveState (key, state) {of state in createBrowserHistory/createHashHistory. Window.sessionStorage.setItem (createKey (key), JSON.stringify (state));} function readState (key) {. Json = window.sessionStorage.getItem (createKey (key)); return JSON.parse (json);} / / createMemoryHistory is only in memory, so the operation is relatively simple const storage = createStateStorage (entries); / / storage = {entry.key: entry.state} function saveState (key, state) {storage [key] = state} function readState (key) {return storage [key]}
Second, the basic principle of react-router
Let's first look at a schematic diagram of react-router, as shown below:
In this process, we can see that in react-router, URL corresponds to Location objects, while UI is determined by react components, which turns into a synchronization problem between location and components.
Third, the concrete realization of react-router
From the above knowledge, we know that if react-router synchronizes URL and UI on the basis of the history library class, it can be divided into this other level to describe the specific steps of implementation:
1. Describe the implementation process at the component level
Let's take a look at the following flow chart:
In this flowchart, we know that the main component is Router RouterContext Link, which only acts as a bridge for the history library.
2. Describe the implementation process at the API level
We can learn about it at the API level through the following flowchart, as shown below:
Summary:
React-router is currently popular and widely used in many projects. Its points can be divided into the following points:
Style: integrated with React, tailor-made for react, the coding style is consistent with react, for example, routing configuration can be achieved through component.
Simplicity: there is no need to manually maintain the routing state, making the code simple.
Powerful: strong routing management mechanism, reflected in the following aspects.
Routing configuration: routing can be configured through components and configuration objects.
Route switching: route switching can be carried out through Redirect.
Route loading: it can be recorded synchronously or loaded asynchronously, so that it can be loaded on demand.
Usage: it can be used not only on the browser side, but also on the server side.
Of course, react-router does not mean that there are no shortcomings, its disadvantage is that API is relatively unstable.
The above is all the contents of the article "how to achieve react-router". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.