最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access current location in reducer (redux-router)? - Stack Overflow

programmeradmin3浏览0评论

How would i get the current path and query of the current location with redux-router in reducer. I am able to get the pathname easily inside the component with mapStateToProps, but i want to access the current path in reducer. I am using redux-router 1.0.0-beta7, react-router 1.0.3.

How would i get the current path and query of the current location with redux-router in reducer. I am able to get the pathname easily inside the component with mapStateToProps, but i want to access the current path in reducer. I am using redux-router 1.0.0-beta7, react-router 1.0.3.

Share Improve this question asked Jun 28, 2016 at 18:52 VikramadityaVikramaditya 5,5747 gold badges36 silver badges46 bronze badges 3
  • 1 maybe you can pass pathname into reducer through action creater? – Kokovin Vladislav Commented Jun 28, 2016 at 18:59
  • 1 Why would you duplicate the "source of truth" of the current path? If you need access to the current path, just get it from props since router is automatically passed. Router is the source of truth for route location, no need to duplicate this in redux. If you need to hear it from the author Redux, watch this: egghead.io/lessons/… – lux Commented Jun 28, 2016 at 19:39
  • this is how redux-router works – Kokovin Vladislav Commented Jun 29, 2016 at 8:55
Add a comment  | 

1 Answer 1

Reset to default 20

1.way - pass pathname with particular action through redux-thunk and getState()

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

2.way - write middleware and pass pathname with every action

///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 - pass pathname from component's this.props.location.pathname

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

//workflow:  component -> action -> reducer
发布评论

评论列表(0)

  1. 暂无评论