En introduktion til Redux-First Routing Model

Et routingbibliotek er en nøglekomponent i ethvert komplekst, enkelt-sideapplikation. Hvis du udvikler webapps med React og Redux, har du sandsynligvis brugt eller i det mindste hørt om React Router. Det er et velkendt routing-bibliotek til React, og en fantastisk løsning til mange brugssager.

Men React Router er ikke den eneste bæredygtige løsning i React / Redux-økosystemet. Faktisk er der masser af routingløsninger bygget til React og Redux, hver med forskellige API'er, funktioner og mål - og listen vokser kun. Det er overflødigt at sige, at routing på klientsiden ikke forsvinder når som helst, og der er stadig meget plads til design i morgendagens routingbiblioteker.

I dag vil jeg henlede opmærksomheden på emnet ruting i Redux. Jeg præsenterer og redegør for Redux-første routing - et paradigme, der gør Redux til stjernen i routing-modellen og den røde tråd blandt mange Redux-routingløsninger. Jeg demonstrerer, hvordan jeg sammensætter kernen, framework-agnostic API i under 100 linjer kode, før jeg udforsker mulighederne for brug i den virkelige verden med React og andre front-end-rammer.

En lille historie

I browseren gemmes placeringen (URL-oplysninger) og sessionshistorikken (en stak af placeringer, der er besøgt af den aktuelle browserfane) i det globale windowobjekt. De er tilgængelige via:

  • window.location (Lokations-API)
  • window.history (Historie-API).

History API tilbyder følgende historiknavigationsmetoder , der er bemærkelsesværdige for deres evne til at opdatere browserens historie og placering uden at det er nødvendigt at genindlæse siden :

  • pushState(href) - skubber en ny placering på historikstakken
  • replaceState(href) - overskriver den aktuelle placering på stakken
  • back() - navigerer til den forrige placering på stakken
  • forward() - navigerer til den næste placering på stakken
  • go(index) - navigerer til et sted på stakken i begge retninger.

Sammen muliggør API'erne History og Location det moderne routing-paradigme på klientsiden kendt som pushState-routing - den første hovedperson i vores historie.

Nu er det næsten en forbrydelse at nævne History og Location API'er uden at nævne et moderne indpakningsbibliotek som history.

ReactTraining / historie

Administrer sessionshistorik med JavaScript github.com

historygiver en enkel, men alligevel kraftfuld API til grænseflade med browserhistorikken og placeringen, mens den dækker uoverensstemmelser mellem forskellige browserimplementeringer. Det bruges som peer eller intern afhængighed i mange moderne routingbiblioteker, og jeg vil gøre flere referencer til det i hele denne artikel.

Redux og pushState-routing

Den anden hovedperson i vores historie er Redux . Det er 2017, så jeg sparer dig for introduktionen og kommer lige til det punkt:

Ved at bruge almindelig pushState-routing i et Redux-program opdeler vi applikationstilstanden på tværs af to domæner: browserhistorik og Redux-butikken.

Sådan ser det ud med React Router, som instantieres og ombrydes history:

history → React Router ↘ view Redux ↗

Nu ved vi, at ikke alle data skal være i butikken. For eksempel er lokal komponenttilstand ofte et passende sted at gemme data, der er specifikke for en enkelt komponent.

Men placeringsdata er ikke trivielle. Det er en dynamisk og vigtig del af applikationstilstanden - den slags data, der hører hjemme i butikken. At holde den i butikken muliggør Redux-luksus som fejlfinding i tidsrejser og nem adgang fra enhver butikstilsluttet komponent.

Så hvordan flytter vi placeringen til butikken?

Der er ingen omgåelse af, at browseren læser og gemmer historik og placeringsoplysninger i window, men hvad vi kan gøre er at opbevare en kopi af placeringsdataene i butikken og holde dem synkroniseret med browseren.

Er det ikke hvad der react-router-reduxgør for React Router?

Ja, men kun for at muliggøre tidsrejser-mulighederne for Redux DevTools. Applikationen afhænger stadig af placeringsdata, der opbevares i React Router:

history → React Router ↘ ↕ view Redux ↗

Brug react-router-reduxtil at læse placeringsdata fra butikken i stedet for React Router frarådes (på grund af potentielt modstridende kilder til sandhed).

Kan vi gøre det bedre?

Kan vi oprette en alternativ rutemodel - en, der er bygget fra bunden til at spille godt med Redux, så vi kan læse og opdatere placeringen på Redux-måde - med store.getState()og store.dispatch()?

Det kan vi absolut, og det kaldes Redux-first routing .

Redux-første routing

Redux-første routing er en variation på pushState-routingdet gør Redux til stjernen i routing-modellen.

En routing-første routing-løsning opfylder følgende kriterier :

  • Placeringen opbevares i Redux-butikken.
  • Placeringen ændres ved at sende Redux-handlinger.
  • Applikationen læser kun placeringsdata fra butikken.
  • Butikken og browserhistorikken holdes synkroniseret bag kulisserne.

Her er en grundlæggende idé om, hvordan det ser ud:

history ↕ Redux → router → view

Vent, er der stadig ikke to kilder til placeringsdata?

Ja, men hvis vi kan stole på, at browserhistorikken og Redux-butikken er synkroniseret, kan vi opbygge vores applikationer til kun nogensinde at læse placeringsdata fra butikken . Fra applikationens synspunkt er der kun én kilde til sandhed - butikken.

Hvordan opnår vi Redux-første routing?

Vi kan starte med at skabe en konceptuel model ved at flette de grundlæggende elementer i routing på klientsiden og Redux-datalevecykelmodeller.

Genbesøg af routing-modellen på klientsiden

Client-side routing is a multi-step process that starts with navigation and ends with renderingrouting itself is only one step in that process! Let’s review the details:

  • Navigation — Everything starts with a change in location. There are 2 types of navigation: internal and external. Internal navigation is accomplished from within the app (eg. via the History API), while external navigation occurs when the user interacts with the browser’s navigation bar or enters the application from an external site.
  • Responding to navigation — When the location changes, the application responds by passing the new location to the router. Older routing techniques relied on polling window.location to accomplish this, but nowadays we have the handy history.listen utility.
  • Routing — Next, the new location is matched to its corresponding page content. The code that handles this step is called a router, and it generally takes an input parameter of matching routes and pages called a route configuration.
  • Rendering — Finally, the content is rendered on the client. This step may, of course, be handled by a front-end framework/library like React.

Note that routing libraries don’t have to handle every part of the routing model.

Some libraries, like React Router and Vue Router, do — while others, like Universal Router, are concerned solely with a single aspect (like routing), thus providing flexibility in the other aspects:

Revisiting the Redux Data Lifecycle Model

Redux boasts a one-way data flow/lifecycle model that likely needs no introduction — but here’s a brief overview for good measure:

  • Action — Any change in state starts by dispatching a Redux action (a plain object containing a type and optional payload).
  • Middleware — The action passes through the store’s chain of middlewares, where actions may be intercepted and additional behaviour may be executed. Middlewares are commonly used to handle side-effects in Redux applications.
  • Reducer — The action then reaches the root reducer, which calculates the store’s next state as a pure function of the previous state and the received action. The root reducer may be composed of individual reducers that each handle a slice of the store’s state.
  • New state — The store saves the new state returned by the reducer, and notifies its subscribers of the change (in React, via connect).
  • Rendering — Finally, the store-connected view may re-render in accordance with the new state.

Building a Redux-First Routing Model

The unidirectional nature of the client-side routing and Redux data lifecycle models lend themselves well to a merged model that satisfies the criteria we laid out for Redux-first routing.

In this model, the router is subscribed to the store, navigation is accomplished via Redux actions, and updates to the browser history are handled by a custom middleware. Let’s examine the details of this model:

  • Internal navigation via Redux actions — Instead of using the History API directly, internal navigation is achieved by dispatching one of 5 navigation actions that mirror the history navigation methods.
  • Updating the browser history via middleware — A middleware is used to intercept the navigation actions and handle the side-effect of updating the browser history. Since the new location isn’t necessarily or easily known without first consulting the browser history (eg. in the case of a go action), the navigation actions are prevented from reaching the reducer.
  • Responding to navigation — The flow of execution continues with a history listener that responds to navigation (from both the middleware and external navigation) by dispatching a second action that does contain the new location.
  • Location Reducer — The action dispatched by the listener then reaches the location reducer, which adds the location to the store. The location reducer also determines the shape of the location state.
  • Connected routing — The store-connected router can then reactively determine the new page content when notified of a change in location in the store.
  • Rendering — Finally, the page may be re-rendered with the new content.

Note that this isn’t the only way to accomplish Redux-first routing — some variations feature the use of a store enhancer and/or additional logic in the middleware — but it’s a simple model that covers all of the bases.

A Basic Implementation

Following the model we just looked at, let’s implement the core API — the actions, middleware, listener, and reducer.

We’ll use the history package as an internal dependency, and build the solution incrementally. If you’d rather follow along with the final result, you may view it here.

Actions

We’ll start by defining the 5 navigation actions that mirror the history navigation methods:

// constants.jsexport const PUSH = 'ROUTER/PUSH';export const REPLACE = 'ROUTER/REPLACE';export const GO = 'ROUTER/GO';export const GO_BACK = 'ROUTER/GO_BACK';export const GO_FORWARD = 'ROUTER/GO_FORWARD';
// actions.jsexport const push = (href) => ({ type: PUSH, payload: href,});
export const replace = (href) => ({ type: REPLACE, payload: href,});
export const go = (index) => ({ type: GO, payload: index,});
export const goBack = () => ({ type: GO_BACK,});
export const goForward = () => ({ type: GO_FORWARD,});

Middleware

Next, let’s define the middleware. It should intercept the navigation actions, call the corresponding history navigation methods, then stop the action from reaching the reducer — but leave all other actions undisturbed:

// middleware.jsexport const routerMiddleware = (history) => () => (next) => (action) => { switch (action.type) { case PUSH: history.push(action.payload); break; case REPLACE: history.replace(action.payload); break; case GO: history.go(action.payload); break; case GO_BACK: history.goBack(); break; case GO_FORWARD: history.goForward(); break; default: return next(action); }};

If you haven’t had the chance to write or examine the internals of a Redux middleware before, check out this introduction.

History Listener

Next, we’ll need a history listener that responds to navigation by dispatching a new action containing the new location information.

First, let’s add the new action type and creator. The interesting parts of the location are the pathname, search, and hash — so that’s what we’ll include in the payload:

// constants.jsexport const LOCATION_CHANGE = 'ROUTER/LOCATION_CHANGE';
// actions.jsexport const locationChange = ({ pathname, search, hash }) => ({ type: LOCATION_CHANGE, payload: { pathname, search, hash, },});

Then let’s write the listener function:

// listener.jsexport function startListener(history, store) { history.listen((location) => { store.dispatch(locationChange({ pathname: location.pathname, search: location.search, hash: location.hash, })); });}

We’ll make one small addition — an initial locationChange dispatch, to account for the initial entry into the application (which doesn’t get picked up by the history listener):

// listener.jsexport function startListener(history, store) { store.dispatch(locationChange({ pathname: history.location.pathname, search: history.location.search, hash: history.location.hash, }));
 history.listen((location) => { store.dispatch(locationChange({ pathname: location.pathname, search: location.search, hash: location.hash, })); });}

Reducer

Next, let’s define the location reducer. We’ll use a simple state shape, and do minimal work in the reducer:

// reducer.jsconst initialState = { pathname: '/', search: '', hash: '',};
export const routerReducer = (state = initialState, action) => { switch (action.type) { case LOCATION_CHANGE: return { ...state, ...action.payload, }; default: return state; }};

Application Code

Finally, let’s hook up our API into the application code:

// index.jsimport { combineReducers, applyMiddleware, createStore } from 'redux'import { createBrowserHistory } from 'history'import { routerReducer } from './reducer'import { routerMiddleware } from './middleware'import { startListener } from './listener'import { push } from './actions'
// Create the history objectconst history = createBrowserHistory()
// Build the root reducerconst rootReducer = combineReducers({ // ...otherReducers, router: routerReducer,}) // Build the middlewareconst middleware = routerMiddleware(history)
// Create the storeconst store = createStore(rootReducer, {}, applyMiddleware(middleware))
// Start the history listenerstartListener(history, store)
// Now you can read location data from the store!let currentLocation = store.getState().router.pathname
// You can also subscribe to changes in the location!let unsubscribe = store.subscribe(() => { let previousLocation = currentLocation currentLocation = store.getState().router.pathname
 if (previousLocation !== currentLocation) { // You can render your application reactively here! }})
// And you can dispatch navigation actions from anywhere!store.dispatch(push('/about'))

And that’s all there is to it! Using our tiny (under 100 lines of code) API, we’ve met all of the criteria for Redux-first routing:

  • The location is held in the Redux store. ✔
  • The location is changed by dispatching Redux actions. ✔
  • The application reads location data solely from the store. ✔
  • The store and browser history are kept in sync behind the scenes. ✔

View all the files together here — feel free to import them into your project, or use it as a starting point to develop your own implementation.

The redux-first-routing package

I’ve also put the API together into the redux-first-routing package, which you may npm install and use in the same way.

mksarge/redux-first-routing

redux-first-routing — A minimal, framework-agnostic base for accomplishing Redux-first routing.github.com

It includes an implementation similar to the one we built here, but with the notable addition of query parsing via the query-string package.

Wait — what about the actual routing component?

You may have noticed that redux-first-routing is only concerned with the navigational aspect of the routing model:

By decoupling the navigational aspect from the other aspects of our routing model, we’ve gained some flexibility — redux-first-routing is both router-agnostic, and framework-agnostic.

You can therefore pair it with a library like Universal Router to create a complete Redux-first routing solution for any front-end framework:

Or, you could build opinionated bindings for your framework of choice — and that’s what we’ll do for React in the next and final section of this article.

Usage with React

Let’s finish our exploration by looking at how we might build store-connected components for declarative navigation and routing in React.

Declarative Navigation

For navigation, we can use a store-connected k/> component similar to the one in React Router and other React routing solutions.

It simply overrides the default behaviour of anchor element <a/> and dispatches a push action when clicked:

// Link.jsimport React from 'react';import { connect } from 'react-redux';import { push as pushAction, replace as replaceAction } from './actions';
const Link = (props) => { const { to, replace, children, dispatch, ...other } = props;
 const handleClick = (event) => { // Ignore any click other than a left click if ((event.button && event.button !== 0) || event.metaKey || event.altKey || event.ctrlKey || event.shiftKey || event.defaultPrevented === true) { return; } // Prevent the default behaviour (page reload, etc.) event.preventDefault();
 // Dispatch the appropriate navigation action if (replace) { dispatch(replaceAction(to)); } else { dispatch(pushAction(to)); } };
 return ( {children} );};
export default connect()(Link);

You may find a more complete implementation here.

Declarative Routing

While there’s not much to a navigational component, there are countless ways to design a routing component — making it the most interesting part of any routing solution.

What is a router, anyway?

You can generally view a router as a function or black box with two inputs and one output:

route configuration ↘ matched content current location ↗

Though the routing and subsequent rendering may occur in separate steps, React makes it easy and intuitive to bundle them together into a declarative routing API. Let’s look at two strategies for accomplishing this.

Strategy 1: A monolithic r/> com ponent

We can use a monolithic, store-connected r/> component that:

  • accepts a route configuration object via props
  • reads the location data from the Redux store
  • calculates the new content whenever the location changes
  • renders/re-renders the content as appropriate.

The route configuration may be a plain JavaScript object that contains all of the matching paths and pages (a centralized route configuration).

Here’s how this might look:

const routes = [ { path: '/', page: './pages/Home', }, { path: '/about', page: './pages/About', }, { path: '*', page: './pages/Error', },]
React.render( , document.getElementById('app'))

Pretty simple, right? No need for nested JSX routes — just a single route configuration object, and a single router component.

If this strategy is appealing to you, check out my more complete implementation in the redux-json-router library. It wraps redux-first-routing and provides React bindings for declarative navigation and routing using the strategies we’ve examined so far.

mksarge/redux-json-router

redux-json-router - Declarative, Redux-first routing for React/Redux browser applications.github.com

Strategy 2: Composable e/> comp onents

While a monolithic component may be a simple way to achieve declarative routing in React, it’s definitely not the only way.

The composable nature of React allows another interesting possibility: using JSX to define routes in a decentralized manner. Of course, the prime example is React Router’s e/> API:

React.render( ... 

Other routing libraries explore this idea too. While I haven’t had the chance do it, I don’t see any reason why a similar API couldn’t be implemented on top of the redux-first-routing package.

Instead of relying on location data provided by

r/>, the &lt;Route/> component could simply connect to the store:

React.render( ... 

If that’s something that you’re interested in building or using, let me know in the comments! To learn more about different route configuration strategies, check out this introduction on React Router’s website.

Conclusion

I hope this exploration has helped deepen your knowledge about client-side routing and has shown you how simple it is to accomplish it the Redux way.

If you’re looking for a complete Redux routing solution, you can use the redux-first-routing package with a compatible router listed in the readme. And if you find yourself needing to develop a tailored solution, hopefully this post has given you a good starting point for doing so.

If you’d like to learn more about client-side routing in React and Redux, check out the following articles — they were instrumental in helping me better understand the topics I covered here:

  • Let The URL Do The Talking by Tyler Thompson
  • You Might Not Need React Router by Konstantin Tarkus
  • Do I Even Need a Routing Library? by James K. Nelson
  • and countless informative discussions in the react-router-redux issues.

Client-side routing is a space with endless design possibilities, and I’m sure some of you have played with ideas similar to the ones I’ve shared here. If you’d like to continue the conversation, I’ll be glad to connect with you in the comments or via Twitter. Thanks for reading!

Edit 22/06/17: Also check out this article on redux-first-router, a separate project that uses intelligent action types to achieve powerful routing capabilities.