问题
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