本文介绍了将路由参数映射到 Redux 存储的键下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

状态对象中有一个位置"键,被多个组件用作数据源.在 URL(与谷歌地图非常相似)中,我有一个名为location"的参数,它是一个坐标.我的目标是将该值(经过一些修改)映射到州的位置"键.如何做到这一点?

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?

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

UPDATEThe 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...

推荐答案

你可以从路由的 onEnter 回调中获取 location 变量参数,然后 dispatch action 到 store.

见上例:

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

这篇关于将路由参数映射到 Redux 存储的键下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:42