简体   繁体   English

react-router v4在页面更改上调度redux操作

[英]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. 我希望在每个react-router页面更改时分派一个动作,然后由reducer截获。

My use case is: I have the page state persisted in redux store. 我的用例是:我的页面状态保存在redux存储中。 The state is represented as {loading, finished} . 状态表示为{loading, finished} When the user clicks a button, a request is made to the server and loading becomes true . 当用户单击按钮时,将向服务器发出请求,并且loading变为true When the response comes back positive loading becomes false and finished becomes true . 当响应返回时,正loading变为falsefinished loading变为true When the user navigates away from the page, I want the state to be reset to its initial values ( loading = false , finished = false ). 当用户离开页面时,我希望将状态重置为其初始值( loading = falsefinished = false )。

The following answer is great, but not work on v4 anymore because onEnter onChange and onLeave were removed. 以下答案很好,但由于已删除onEnter onChangeonLeave ,因此不再适用于v4。

React Router + Redux - Dispatch an async action on route change? React Router + Redux-在路由更改时分派异步操作?

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! 谢谢!

You could create your history instance separately, and listen to that and dispatch an action when something changes. 您可以单独创建history实例,然后监听并在发生更改时调度操作。

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>
    )
  }
}

v4 has the location object which could be used to check if the app has navigated away from the current page. v4具有location对象,可用于检查应用程序是否已离开当前页面。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM