How use redux state with routes react-router?

2019-08-21 19:42发布

问题:

I created my routes

<Provider store={store}>
    <Router history={browserHistory}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>

My problem is when I dispatch an action from redux component , the props changed in the /redux route but in the / always the initial state. Please who can help me ?

回答1:

Try to use react-router-redux (https://github.com/reactjs/react-router-redux) to synchronise redux store with react-router.

import { browserHistory } from 'react-router';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import { createStore, combineReducers } from 'redux';

// Add router reducer to your store on the `routing` key
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)
// Create enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);

...

<Provider store={store}>
    <Router history={history}>
        <Route path="/" component={App}>
        <Route path="/redux" component={redux} />
    </Router>
</Provider>