我将如何在 reducer 中使用 redux-router 获取当前路径和查询当前位置。我可以使用 mapStateToProps 在组件内轻松获取路径名,但我想访问 reducer 中的当前路径。我正在使用 redux-router 1.0.0-beta7,react-router 1.0.3。
如何访问减速器(redux-router)中的当前位置?
IT技术
javascript
reactjs
redux
react-router
router
                    2021-05-11 10:47:53
                
                    
                
            
        1个回答
            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 - 从组件的 this.props.location.pathname 传递路径名
//in component 
let {pathname}= this.props.location;
this.props.someAction(data, pathname);
//workflow:  component -> action -> reducer