Skip to content Skip to sidebar Skip to footer

React-router V4 Dispatch Redux Action On Page Change

I would like an action to be dispatched and then intercepted by the reducers on every react-router page change. My use case is: I have the page state persisted in redux store. The

Solution 1:

You could create your history instance separately, and listen to that and dispatch an action when something changes.

Example

// history.jsimport createHistory from'history/createBrowserHistory';

const history = createHistory();

history.listen(location => {
  // Dispatch action depending on location...
});

exportdefault history;

// App.jsimport { Router, Route } from'react-router-dom';
importHomefrom'./components/Home';
importLoginfrom'./components/Login';
import history from'./history';

classAppextendsReact.Component {
  render() {
    return (
      <Routerhistory={history}><div><Routeexactpath="/"component={Home} /><Routepath="/login"component={Login} /></div></Router>
    )
  }
}

Solution 2:

v4 has the location object which could be used to check if the app has navigated away from the current page.

https://reacttraining.com/react-router/web/api/location

Post a Comment for "React-router V4 Dispatch Redux Action On Page Change"