首页 文章

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

提问于
浏览
1

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

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

以下答案很棒,但不再适用于 v4,因为删除了onEnter onChangeonLeave

React Router Redux - 在路由更改时调度异步操作?

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

谢谢!

2 回答

  • 2

    您可以单独创建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>
        )
      }
    }
    
  • 0

    v4 具有location对象,可用于检查应用程序是否已离开当前页面。

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

相关问题