react-router v4 dispatch redux action on page change

这一生的挚爱 提交于 2020-01-24 15:56:47

问题


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 state is represented as {loading, finished}. When the user clicks a button, a request is made to the server and loading becomes true. When the response comes back positive loading becomes false and finished becomes true. When the user navigates away from the page, I want the state to be reset to its initial values (loading=false, finished=false).

The following answer is great, but not work on v4 anymore because onEnter onChange and onLeave were removed.

React Router + Redux - Dispatch an async action on route change?

Edit: The best solution would be something scalable. In the future there would be multiple such pages and the state for each of them should reset on page nagivation

Thank you!


回答1:


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

Example

// history.js
import createHistory from 'history/createBrowserHistory';

const history = createHistory();

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

export default history;

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

class App extends React.Component {
  render() {
    return (
      <Router history={history}>
        <div>
          <Route exact path="/" component={Home} />
          <Route path="/login" component={Login} />
        </div>
      </Router>
    )
  }
}



回答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



来源:https://stackoverflow.com/questions/51109067/react-router-v4-dispatch-redux-action-on-page-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!