react-router v4 在页面更改时调度 redux 操作 [英] react-router v4 dispatch redux action on page change

查看:23
本文介绍了react-router v4 在页面更改时调度 redux 操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在每次 react-router 页面更改时分派一个动作,然后由减速器拦截.

我的用例是:我将页面状态保存在 redux 存储中.状态表示为 {loading,finished}.当用户单击按钮时,会向服务器发出请求,loading 变为 true.当响应返回正面时,loading 变为 falsefinished 变为 true.当用户离开页面时,我希望将状态重置为其初始值 (loading=false, finished=false).

以下答案很好,但不再适用于 v4,因为 onEnter onChangeonLeave 已被删除.

React Router + Redux - 调度异步操作路线变更?

最好的解决方案是可扩展的.将来会有多个这样的页面,每个页面的状态都应该在页面导航时重置

谢谢!

解决方案

您可以单独创建您的 history 实例,并在发生变化时监听并调度操作.

示例

//history.js从'history/createBrowserHistory'导入createHistory;const 历史 = createHistory();history.listen(位置=> {//根据位置分派动作...});导出默认历史记录;//App.js从'react-router-dom'导入{路由器,路由};从'./components/Home'导入Home;从'./components/Login'导入登录;从 './history' 导入历史记录;类 App 扩展了 React.Component {使成为() {返回 (<路由器历史={历史}><div><路由精确路径="/" component={Home}/><Route path="/login" component={Login}/>

</路由器>)}}

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!

解决方案

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

这篇关于react-router v4 在页面更改时调度 redux 操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆