项目作者: mksarge

项目描述 :
Declarative, Redux-first routing for React/Redux browser applications.
高级语言: JavaScript
项目地址: git://github.com/mksarge/redux-json-router.git
创建时间: 2017-04-02T06:06:45Z
项目社区:https://github.com/mksarge/redux-json-router

开源协议:MIT License

下载


Changes in version 1.x

State Shape

redux-json-router now uses the redux-first-routing package internally, following its state shape:

  1. // URL: www.example.com/nested/path?with=query#and-hash
  2. {
  3. router: {
  4. pathname: '/nested/path/',
  5. search: '?with=query',
  6. queries: {
  7. with: 'query'
  8. },
  9. hash: '#and-hash'
  10. },
  11. ... // other redux state
  12. }

The optional replace prop was removed. Instead, you can now specify the desired navigation action via the action prop:

  1. <Link to="/about" /> // default: dispatches a push action
  2. <Link to="/about" action="replace" /> // dispatches a replace action
  3. <Link action="goBack" /> // dispatches a goBack action
  4. <Link action="goForward" /> // dispatches a goForward action

Redux JSON Router

build status
npm version

redux-json-router is a minimal router intended for use with client-rendered React/Redux applications.

Features

  • Declarative routing — The routing configuration is defined declaratively with JSON, or with plain JavaScript.
  • Redux-first routing — The URL is just a regular part of Redux state, and can be updated by dispatching actions.
  • Practical handling of browser history — The URL held in the browser history and Redux store stay in sync behind the scenes, so that the UI can always trust the URL in the store as its source of truth.
  • Code-splitting — Code-splitting and asynchronous loading of routes is easily enabled with a webpack loader.
  • React bindings<Router></Router> for matching/loading/rendering routes, and <Link/> for push/replace navigation.

Motivation

Background

I know what you’re thinking - yet another React/Redux router? Really?

Yes, there are many existing solutions out there already. Of course, you already know react-router. But you may have also heard of solutions like redux-little-router or universal-router.

Every router has its strengths - and, as with any library, choosing a router comes down to finding the one that best suits your needs. Here are some of the categories that similar routers target:

  • Environment: Browser-only, or universal
  • Libraries: React-only, Redux (React optional), or other
  • Routing config: JSX, plain JS, or JSON-based

redux-json-router similarly targets a subset of the above categories. It attempts to answer the question: What is the minimal API needed in a Redux-first router for client-rendered React/Redux applications with a JSON-based routing configuration?

Redux-First Routing

Key point: Like with any other complex/dynamic state, the application view should depend solely on the URL held in the Redux store (a single source of truth).

In modern browsers, the URL state and history are held in window.location and window.history. We can manipulate the browser history directly using the history API, but even better, we can utilize the awesome history module to accomplish this.

Without Redux-first routing, a React/Redux application view may depend on URL state from outside of the store, like this:

  1. # using react-router:
  2. history React Router
  3. View
  4. Redux
  5. # using react-router + react-router-redux:
  6. history React Router
  7. View
  8. Redux

With Redux-first routing, a React/Redux application view depends solely on the URL from the Redux store.

  1. # using redux-json-router:
  2. history
  3. Redux View

redux-json-router accomplishes Redux-first routing by making the URL a regular part of the state tree, allowing Redux actions to dispatch URL changes, and keeping the store and browser history in sync behind the scenes.

Here’s what the URL looks like on the state tree:

  1. // current URL: https://www.website.com/redux/json/router?is=cool#yup
  2. // previous URL: https://www.website.com/previous/route
  3. {
  4. ..., // other redux state
  5. router: {
  6. url: '/redux/json/router?is=cool#yup',
  7. hash: 'yup',
  8. queries: {
  9. is: 'cool'
  10. },
  11. paths: [
  12. 'redux',
  13. 'json',
  14. 'router'
  15. ],
  16. previous: {
  17. url: '/previous/route',
  18. hash: '',
  19. queries: {},
  20. paths: [
  21. 'previous',
  22. 'route'
  23. ]
  24. }
  25. }
  26. }

Installation

  1. npm install --save redux-json-router

API

redux-json-router has a reasonably small API. Here’s a look at the exports in src/index.js:

  1. // History API
  2. export { createBrowserHistory } from './history/createBrowserHistory';
  3. export { startListener } from './history/startListener';
  4. // Redux API
  5. export { routerMiddleware } from './redux/middleware';
  6. export { routerReducer } from './redux/reducer';
  7. export { push, replace, go, goBack, goForward, manualChange } from './redux/actions';
  8. export { PUSH, REPLACE, GO, GO_BACK, GO_FORWARD, MANUAL_CHANGE } from './redux/constants';
  9. // React API
  10. export { RouterContainer as Router } from './react/Router';
  11. export { LinkContainer as Link } from './react/Link';
  12. /* The webpack loader 'route-loader' is not exported here.
  13. Import it directly into your webpack config, following the instructions below. */
  • History API
  • Redux API
    • routerMiddleware(history)
      • intercepts router actions (push, replace, go, goBack and goForward) to update the browser history, before continuing/breaking the middleware chain
    • routerReducer
      • parses and adds the URL to the Redux state
    • routerActions
      • used to dispatch URL updates; middleware intercepts and calls equivalent history navigation actions
        • push(href) — updates the current and previous URL in the Redux state
        • replace(href) — updates the current URL, but not the previous URL, in the Redux state
        • go(index) — intercepted by routerMiddleware; startListener subsequently dispatches manualChange action
        • goBack() — intercepted by routerMiddleware; startListener subsequently dispatches manualChange action
        • goForward() — intercepted by routerMiddleware; startListener subsequently dispatches manualChange action
        • manualChange(href) — updates the current and previous URL in the Redux state
    • routerConstants
      • public action types for use in user-defined middleware
  • React components
    • <Router></Router>
      • matches the current URL with the routing configuration, loads, then renders the page
      • props:
    • <Link/>
      • used for internal navigation (as opposed to <a></a>, for external navigation)
      • props:
        • to (string) — required; the internal URL (pathname + query + hash) to navigate to (eg. '/about', '/blog?posted=2017', '/blog/post/1#introduction')
        • replace (boolean) — optional; set to true for the link to dispatch a replace action (default: push)
        • onClick (function) — optional; specify a callback to run on click, before the push/replace action is dispatched
  • Webpack loader (optional)
    • route-loader
      • translates a .json routing configuration file into JavaScript; see Routing Configuration for acceptable JSON, and Webpack Configuration for set-up instructions
      • options:
        • debug (boolean) — optional; if true, logs the output to the console (default: false)
        • chunks (boolean) — optional; if true, splits routes without a specified chunk property into [separate chunks][code-splitting]; if false, adds pages without a specified chunk into the main code chunk (default: true)

Usage

Let’s look at how we’d add redux-json-router to a React/Redux application. We’ll only make a few changes:

  • Routing config — We’ll define the routes in a routes.json or routes.js file.
  • Redux config — We’ll add the Redux reducer and middleware to the store.js configuration file.
  • App entry point — We’ll add a bit of boilerplate to index.js and render the app with <Router></Router>.
  • Webpack config (optional) — To load routes.json, we’ll add a custom loader to webpack.config.js.

Routing Configuration

Declare your routes in a routes.json file with an array of “route objects”:

  1. // routes.json
  2. [
  3. {
  4. "path": "/", // an exact path
  5. "page": "./pages/Home",
  6. "chunk": "main"
  7. },
  8. {
  9. "path": "/docs",
  10. "page": "./pages/Docs",
  11. "chunk": "main",
  12. "children": [
  13. {
  14. "path": "/:id", // a nested and parameterized path
  15. "page": "./pages/Post"
  16. }
  17. ]
  18. },
  19. {
  20. "path": "*", // a catch-all path
  21. "page": "./pages/Error"
  22. }
  23. ]

Route objects are defined as follows:

  1. type RouteObject {
  2. path: string, // Required. Specifies the path name (options: exact, param, or catch-all).
  3. page: string, // Required. Specifies the React component to be instantiated.
  4. chunk?: string, // Optional. Specifies the code chunk to be loaded in (default: separate chunks for all pages).
  5. children?: [RouteObject] // Optional. Specifies any nested routes.
  6. }

The bundled webpack loader is used to translate routes.json into JavaScript that can be read by the <Router></Router> component. Alternatively, you may choose to write the routing config in JavaScript yourself:

  1. // routes.js - equivalent to routes.json above
  2. export default [
  3. {
  4. path: '/',
  5. load: () => Promise.resolve(require('./pages/Home').default), // file loaded in the main code chunk
  6. },
  7. {
  8. path: '/docs',
  9. load: () => Promise.resolve(require('./pages/Docs').default), // file loaded in the main code chunk
  10. children: [
  11. {
  12. path: '/:id',
  13. load: () => new Promise((resolve, reject) => {
  14. try {
  15. require.ensure(['./pages/Post'], (require) => { // file loaded in a separate code chunk
  16. resolve(require('./pages/Post').default);
  17. });
  18. } catch (err) {
  19. reject(err);
  20. }
  21. }),
  22. },
  23. ],
  24. },
  25. {
  26. path: '*',
  27. load: () => new Promise((resolve, reject) => {
  28. try {
  29. require.ensure(['./pages/Error'], (require) => { // file loaded in a separate code chunk
  30. resolve(require('./pages/Error').default);
  31. });
  32. } catch (err) {
  33. reject(err);
  34. }
  35. }),
  36. },
  37. ];

Redux Configuration

In your Redux config, add routerReducer to the root reducer under the router key, and add routerMiddleware to your Redux middlewares, passing it the history singleton created in the application entry point (as shown in the following section).

  1. // store.js
  2. import { combineReducers, applyMiddleware, compose, createStore } from 'redux';
  3. import { routerReducer, routerMiddleware } from 'redux-json-router';
  4. import { otherReducers, otherMiddlewares } from './other';
  5. // add `routerReducer` to your root reducer
  6. const makeRootReducer = () => combineReducers({
  7. ...otherReducers,
  8. router: routerReducer
  9. });
  10. function configureStore(history, initialState = {}) {
  11. // add `routerMiddleware` to your middlewares, passing it the history singleton from the app's entry point
  12. const middlewares = [...otherMiddlewares, routerMiddleware(history)];
  13. const enhancers = [applyMiddleware(...middlewares)];
  14. return createStore(makeRootReducer(), initialState, composeEnhancers(...enhancers));
  15. }

Application Entry Point

In your app’s entry point, import the routing config, create the history singleton, create the store with the history singleton, and call startListener to initialize the router state in the store and start listening for external actions. Finally, render the application using <Router></Router> inside the Redux <Provider></Provider>.

  1. // index.js
  2. import React from 'react';
  3. import { render } from 'react-dom';
  4. import { Provider } from 'react-redux';
  5. import { createBrowserHistory, startListener, Router } from 'redux-json-router';
  6. import configureStore from './store';
  7. import routes from './routes.json'; // webpack-loaded JSON routing config
  8. // import routes from './routes'; // plain JavaScript routing config
  9. // create a history singleton
  10. const history = createBrowserHistory();
  11. // configure store with history
  12. const store = configureStore(history);
  13. // dispatch actions when the history is manually changed (with navigation buttons / address bar)
  14. startListener(history, store);
  15. // render the application with <Router ></Router> to match the current URL to the routing config
  16. render(
  17. <Provider store={store}>
  18. <Router routes={routes} ></Router>
  19. </Provider>,
  20. document.getElementById('app'));

Webpack Configuration (Optional)

To use the included webpack loader, import route-loader directly into your webpack config:

  1. // webpack.config.js
  2. const routes = [path.resolve(__dirname, './app/routes.json')]; // the path to your JSON routing config
  3. const config = {
  4. ...,
  5. module: {
  6. rules: [
  7. ...,
  8. {
  9. test: /\.json$/,
  10. exclude: routes, // exclude routes.json from being loaded by the usual json-loader
  11. loader: 'json-loader',
  12. },
  13. {
  14. test: /\.json$/,
  15. include: routes, // load routes.json with route-loader instead
  16. loader: 'redux-json-router/lib/route-loader',
  17. options: {
  18. // debug (boolean) - defaults to false
  19. // chunks (boolean) - defaults to true
  20. },
  21. },
  22. ...

Credits

This project was heavily inspired by similar work and research on JavaScript/React/Redux routing including:

Contributing

Contributions are welcome and are greatly appreciated!

Feel free to file an issue, start a discussion, or send a pull request.

License

MIT

[url-talking]: https://formidable.com/blog/2016/07/11/let-the-url-do-the-talking-part-1-the-pain-of-react-router-in-redux

[code-splitting]: https://webpack.js.org/guides/code-splitting-async