React Router v4与Redux集成异常:路由组件无法获取props
解决React Router v4与Redux集成后路由组件无法获取props的问题
看起来你的核心问题出在**react-router-redux与React Router v4不兼容**上——这个包仅支持到React Router v3,在v4版本中需要使用connected-react-router来实现Redux和路由的无缝集成。另外你的代码里还有几处细节需要调整,下面是具体的解决步骤:
1. 替换依赖包
首先卸载旧的react-router-redux,安装适配React Router v4的connected-react-router:
npm uninstall react-router-redux npm install connected-react-router
2. 修改Store创建逻辑(index.js)
需要用connected-react-router提供的工具来配置store,确保路由状态能正确同步到Redux:
import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import { createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import { routerMiddleware } from 'connected-react-router'; import { createLogger } from 'redux-logger'; import thunk from 'redux-thunk'; import { createBrowserHistory } from 'history'; import { connectRouter } from 'connected-react-router'; import reducers from './reducers'; const history = createBrowserHistory(); const logger = createLogger(); const middleware = [ thunk, routerMiddleware(history) // 使用connected-react-router的路由中间件 ]; if (process.env.NODE_ENV === 'development') { middleware.push(logger); } // 合并路由reducer和自定义reducer const store = createStore( connectRouter(history)(reducers), compose( applyMiddleware(...middleware), // 可选:添加Redux DevTools支持 window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() ) ); render( <Provider store={store}> <Router history={history}> {/* 传入history实例 */} <App /> </Router> </Provider>, document.getElementById('root') );
3. 调整Reducers配置(reducers/index.js)
不再需要手动添加routerReducer,connectRouter已经自动处理了路由状态的管理:
import { combineReducers } from 'redux'; // 移除react-router-redux的导入 import pages from './pages'; import posts from './posts'; export default combineReducers({ pages, posts // 移除原有的routing: routerReducer配置 });
4. 简化App.js的Switch配置
你不需要手动给Switch传递location属性,React Router会自动处理路由上下文:
import React, { Component } from 'react'; import { Switch, Route, Link, withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import Home from './components/Home'; import About from './components/About'; // 导入其他组件、actions和路由常量 class App extends Component { componentDidMount() { this.props.fetchPages(API_PAGES); this.props.fetchPosts(API_POSTS); } render() { return ( !this.props.pages.isFetching ? ( <div> <ul> {this.props.pages.data && this.props.pages.data.map(page => ( <li key={page.id}> <Link to={page.slug}>{page.title.rendered}</Link> </li> ))} </ul> {/* 移除location={this.props.location} */} <Switch> <Route path={routes.HOME} exact component={Home} /> <Route path={routes.ABOUT} component={About} /> <Route path={routes.CONTACT} component={Contact} /> <Route path={routes.NEWS} component={News} /> <Route component={NotFound} /> </Switch> </div> ) : ( <p>Loading...</p> ) ); } } function mapStateToProps(state) { return state; } // 保持withRouter包裹connect的顺序不变 export default withRouter(connect( mapStateToProps, { ...actions } )(App));
5. 确保路由组件能获取Props
如果你的Home组件需要访问路由相关的props(如match、location、history),可以通过两种方式实现:
- 方式一:用
withRouter直接包裹组件:
import React from 'react'; import { withRouter } from 'react-router-dom'; const Home = (props) => { console.log('home', props); // 现在能看到路由相关props了 return ( <div> This is the home page. </div> ); }; export default withRouter(Home);
- 方式二:如果组件需要连接Redux,确保
withRouter在最外层:
import React from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; const Home = (props) => { console.log('home', props); return ( <div> This is the home page. </div> ); }; export default withRouter(connect(mapStateToProps)(Home));
做完这些调整后,你的Home组件应该就能正常获取到props了。核心问题就是旧的react-router-redux不兼容React Router v4,换成connected-react-router就能解决大部分集成问题。
内容的提问来源于stack exchange,提问作者Ruud Luijten
相关产品推荐
相关产品推荐

