The Principles Behind Front-end Routing #128
zhangyu1818
announced in
en
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Libraries like
react-router
fundamentally depend on a package calledhistory
.history
is essentially a wrapper for the nativewindow.history
API.window.history API
window.history
provides five methods:go
: Navigate to a specific page; the parameter is a number.go(1)
goes forward one page,go(-1)
goes back one page.back
: Equivalent togo(-1)
.forward
: Equivalent togo(1)
.pushState
: Adds a new history record.replaceState
: Replaces the current history record.We mainly use
pushState
andreplaceState
.pushState
The
pushState
method takes three arguments.state
object.url
, which is displayed in the browser's address bar in real-time.The state object can be accessed via
window.history.state
and defaults tonull
.To demonstrate, open the browser's console on the current page and type
window.history.pushState({state:0},"","/page")
. You'll notice the browser address changes to/page
.Run
window.history.state
in the console; you'll see{state: 0}
.Run
window.history.back()
to go back a page.replaceState
The key difference between
replaceState
andpushState
is thatreplaceState
replaces the current history record.Open your console and type
window.history.replaceState({state:1},"","/replace")
. You'll notice the browser address changes to/replace
.Type
window.history.state
in the console to retrieve the current{state: 1}
.Type
window.history.back()
to navigate to the previous page because the last one was replaced by us.Tracking History Changes
The browser provides a
popstate
event to listen to history changes. However, this cannot track changes made bypushState
orreplaceState
, nor can it determine the direction of navigation (forward or backward). It tracks only changes viago
,back
,forward
, and browser navigation buttons.A Brief Dive into history's Source Code
The history library solves the limitations of native listeners. It unifies these various APIs into a single
history
object and independently implements listener functionality. When callingpush
orreplace
, it triggers the associated event callback functions and passes in the direction of navigation.You'll notice that it merely creates its own
listeners
array and manually invokes them duringpush
andreplace
, thereby addressing the issues of native APIs not triggering these events.createHashHistory
is almost identical tocreateBrowserHistory
, but it additionally listens forhashchange
events.Implementing React Router from Scratch
Based on these principles, we can already write a simple router.
Below is a straightforward 20-line implementation example.
In essence, different
pathname
are used to display different elements. However,react-router
includes more complex conditions and logic. A more detailed analysis of its source code will be published soon.Beta Was this translation helpful? Give feedback.
All reactions