Display the route parameter under the Redux repository key

The state object has a “location” that is used by several components as a data source. In the url (very similar to google maps) I have the parameter "location" which is the coordinate. My goal is to map this value (with some modification) to the location state. How to do it?

UPDATE The only way I could imagine was to create middleware and respond to route actions, somehow extract parameters from the URL, and then send a new action that will be processed by the reducer. Or just use a gearbox without the need for additional middleware. But I think this is not a very good approach ...

0
source share
2 answers

You can get the locationvariable parameters from the onEntercallback of your route, and then send the action to save.

See the example above:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import App from './App';
import { Route, Router, browserHistory } from 'react-router';

const store = createStore(rootReducer);

const routes = (
  <Route
    path="/location/:location"
    component={App}
    onEnter={handleEnter}
  />
);

function rootReducer(state = {
  location: {},
}, action) {
  switch (action.type) {
    case 'ADD_TO_LOCATION':
      return {
        ...state,
        location: action.location,
      };
    default:
      return state;
  }
  return state;
}

function handleEnter(nextState) {
  // Map location data here.
  // Next, we are dispatching mapped location to store.
  store.dispatch({
    type: 'ADD_TO_LOCATION',
    location: nextState.params.location,
  });
}

ReactDOM.render(<Router routes={routes} history={browserHistory} />, document.getElementById('root'));
+1
source

, componentWillReceiveProps , window.location.href . github repo. -. : @@routerParams/URL_UPDATE action.payload.

-1

All Articles