【问题标题】:react-router v4 dispatch redux action on page changereact-router v4 在页面更改时调度 redux 操作
【发布时间】:2018-12-09 01:57:30
【问题描述】:

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

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

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

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

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

谢谢!

【问题讨论】:

    标签: javascript reactjs redux react-router


    【解决方案1】:

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

    示例

    // 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 具有location 对象,可用于检查应用是否已离开当前页面。

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

      【讨论】:

      • 感谢您的回答。我读了那页。您如何建议可以使用location 对象进行此类检查?
      猜你喜欢
      • 2018-07-16
      • 2016-09-21
      • 2018-10-28
      • 2017-09-12
      • 1970-01-01
      • 2017-12-05
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多