【问题标题】:Map a route parameter to under a Redux store's key将路由参数映射到 Redux 存储的键下
【发布时间】:2016-11-03 20:39:05
【问题描述】:

状态对象中有一个“位置”键,被多个组件用作数据源。在 URL(非常类似于谷歌地图)中,我有一个名为“位置”的参数,它是一个坐标。我的目标是将该值(经过一些修改)映射到该州的“位置”键。该怎么做?

更新 我能想象的唯一方法是创建一个中间件并对路由操作做出反应,以某种方式从 URL 中提取参数,然后调度一个将由 reducer 处理的新操作。或者只使用 reducer,不需要额外的中间件。但我想这不是一个好方法......

【问题讨论】:

    标签: reactjs redux react-router react-router-redux


    【解决方案1】:

    您可以从路由的onEnter 回调中获取location 变量参数,然后将操作分派到存储。

    参见上面的示例:

    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】:

      我已经为根路由创建了容器,它在 componentWillReceiveProps 事件中获取路由器参数,如果 window.location.href 没有太多先前的状态,则将它们分派到商店。您可以在github repo 上查看代码。 我使用 redux-saga。因此,我最好只听我的自定义事件:@@routerParams/URL_UPDATE 并从 action.payload 中获取所有参数。

      【讨论】:

        猜你喜欢
        • 2014-05-23
        • 2019-03-29
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        • 1970-01-01
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多