React+Redux中如何正确使用routerMiddleware将history传递给redux store
问题解决方法
错误原因
现有代码的核心问题是connected-react-router的根reducer定义语法错误:connectRouter要求你定义一个接收history作为入参的根reducer函数,函数内部再执行combineReducers注册路由reducer,当前写法把combineReducers的返回值直接当成了可接收history参数的函数调用,属于语法使用错误。
另外react-admin默认会内部创建history实例,你需要手动把自己定义的history实例传递给Admin组件,否则redux里的路由状态和实际页面路由无法同步。
修正后的代码
1. 修正store配置
import { createStore, combineReducers, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import { composeWithDevTools } from 'redux-devtools-extension' import { routerMiddleware, connectRouter } from 'connected-react-router' import { createBrowserHistory } from 'history' import { postListReducer } from './reducers/postReducers' export const history = createBrowserHistory() // 定义为接收history参数的函数,内部返回combineReducers结果 const rootReducer = (history) => combineReducers({ postList: postListReducer, router: connectRouter(history), }) const initialState = { postList: { posts: [] } } const middleware = [thunk, routerMiddleware(history)] const store = createStore( rootReducer(history), // 传入history生成最终的根reducer initialState, composeWithDevTools(applyMiddleware(...middleware)) ) export default store
2. 给react-admin的Admin组件传递history
在项目入口引入上面导出的history,传给Admin组件覆盖默认实例:
import { Admin } from 'react-admin' import { history } from './store' // 替换为你的store文件实际路径 const App = () => { return ( <Admin history={history} {/* 其余配置如dataProvider、layout等保持不变 */}> {/* 原有资源配置 */} </Admin> ) }
使用方式
配置完成后可通过两种方式操作路由:
- 任意位置直接导入
history实例调用history.push('/path')、history.goBack()等方法 - 在action中使用connected-react-router提供的路由action:
import { push } from 'connected-react-router' // thunk action示例 export const createPost = (data) => async (dispatch) => { // 接口请求等业务逻辑 dispatch(push('/post-list')) }
内容的提问来源于stack exchange,提问作者Sunil Shrestha
相关产品推荐
相关产品推荐

