Map a route parameter to under a Redux store's key

霸气de小男生 提交于 2020-01-07 06:27:07

问题


There is a "location" key in the state object which is used by multiple components as data source. In the URL (very similar to google maps) I have a parameter called "location" which is a coordinate. My goal is to map that value (with some modification) to the state's "location" key. How to do that?

UPDATE The only way I could imagine is to create a middleware and react to route actions, extract the parameters from the URL somehow, then dispatch a new action that will be processed by a reducer. Or just use a reducer, not necessary having an extra middleware. But I guess this is not a good approach...


回答1:


You can get location variable params from onEnter callback of your route, and then dispatch action to store.

See 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'));



回答2:


I've created container for the root route which takes router params on componentWillReceiveProps event and dispatch them to the store if window.location.href doesn't much previous state. You can see the code on github repo. I use redux-saga. Therefore it's better for me just to listen to my custom event: @@routerParams/URL_UPDATE and take all params from action.payload.



来源:https://stackoverflow.com/questions/38145321/map-a-route-parameter-to-under-a-redux-stores-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!