问题
I'm running into an issue where ConnectedRouter is not updating history on route change. On route change store gets updated history and Router (ConnectedRouter's child) gets updated history but ConnectedRouter's history stays same. The app doesn't render new component but the browser's url changes.
index
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { ConnectedRouter } from 'react-router-redux'
import AppContainer from './containers/app'
import { history, store } from './store'
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<AppContainer />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
)
store
import createHistory from 'history/createBrowserHistory'
import { createStore, applyMiddleware, compose } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import { rootReducer } from './reducers/root'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
export const history = createHistory()
const middleware = routerMiddleware(history)
export const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(middleware))
)
rootReducer
import { combineReducers } from 'redux'
import { routerReducer } from 'react-router-redux'
export const rootReducer = combineReducers({
router: routerReducer,
})
HeaderContainer
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { push } from "react-router-redux"
import { HeaderTemplate } from '../components/templates/header'
const mapStateToProps = state => ({})
const mapDispatchToProps = dispatch =>
bindActionCreators({
pushRoute: location => dispatch(push(location)),
}, dispatch)
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(HeaderTemplate)
)
HeaderTemplate
import React from 'react'
export const HeaderTemplate = props => (
<div className="content">
<nav>
<ul>
<SomeLink onClick={() => props.pushRoute('/')}>Link1</SomeLink>
<SomeLink onClick={() => props.pushRoute('/test')}>Link2</SomeLink>
</ul>
</nav>
</div>
)
回答1:
It looks like what you are doing is wrapping the HeaderContainer with the withRouter
but you should actually be wrapping the AppContainer with that assuming that the AppContainer has the actual <Route />
's inside of it.
Other than that the only thing I would say is to make sure you ran:
npm install --save react-router-redux@next
in order to user the ConnectedRouter
回答2:
The question is a little confusing but I think I know your problem. I don't believe Router can be a child of ConnectedRouter, You need to REPLACE Router with ConnectedRouter and everything will work as expected.
来源:https://stackoverflow.com/questions/44093898/react-router-redux-connectedrouter-not-updating-with-route-change