如何访问reducer(redux-router)中的当前位置?

时间:2016-06-28 18:52:42

标签: javascript reactjs redux react-router router

如何使用reducer中的redux-router获取当前路径并查询当前位置。我可以使用mapStateToProps在组件内轻松获取路径名,但我想访问reducer中的当前路径。我使用的是redux-router 1.0.0-beta7,react-router 1.0.3。

1 个答案:

答案 0 :(得分:15)

1 .way - 通过 redux-thunk 和getState()传递路径名以及特定的操作

const someAction = data =>(dispatch,getState)=>{
   dispatch({
      type:'SOME_ACTION',
      pathname:getState().router.pathname
   })
}

2 .way - 编写中间件并在每次操作时传递路径名

///write middleware
export const attachPathNameToAction = store => next => action=>{
    action.pathname = store.getState().router.pathname //<-----passing pathname
    next(action)
};


///then in reducer you allways can get pathname
case 'SOME_ACTION':
    let pathname = action.pathname \\  <-------------
    return {...state, action.data}

3 .way - 从组件传递路径名&lt; props.location.pathname

//in component 
let {pathname}= this.props.location;
this.props.someAction(data, pathname);

//workflow:  component -> action -> reducer