【问题标题】:How to access current location in reducer (redux-router)?如何访问减速器(redux-router)中的当前位置?
【发布时间】:2016-10-31 05:57:05
【问题描述】:

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

【问题讨论】:

  • 也许你可以通过action creater将路径名传递给reducer?
  • 为什么要复制当前路径的“真实来源”?如果您需要访问当前路径,只需从props 获取它,因为router 会自动传递。 Router 是路由定位的真实来源,不需要在 redux 中重复这个。如果您需要从作者 Redux 那里听到它,请观看:egghead.io/lessons/…
  • redux-router 是这样工作的

标签: javascript reactjs redux react-router router


【解决方案1】:

1.way - 通过 redux-thunk 和 getState() 传递具有特定 actionpathname p>

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 - 从组件的 this.props.location.pathname 传递路径名

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

//workflow:  component -> action -> reducer

【讨论】:

  • 中间件解决方案很棒!感谢那。我真的很想知道为什么他们没有插件。
  • 请注意,它是... .router.location.pathname,而不是... .router.pathname
猜你喜欢
  • 2016-12-26
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 2015-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多