Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router Redux ConnectedRouter Not Updating With Route Change

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>
)
like image 551
cocacrave Avatar asked Oct 29 '25 01:10

cocacrave


1 Answers

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

like image 127
LoganRx Avatar answered Oct 31 '25 11:10

LoganRx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!