简体   繁体   English

React flux拦截器实现

[英]React flux interceptor implementation

反应通量架构是否与Angular的拦截器类似,您可以将401错误重定向到登录页面?

Not specifically, but you can handle it in your ajax request error callback. 不是特别的,但你可以在你的ajax请求错误回调中处理它。 Check for a 401 response, render your login component/redirect to login. 检查401响应,呈现登录组件/重定向登录。 With facebook's flux implementation i've typically kept my ajax calls inside the actions. 有了facebook的flux实现,我通常会在动作中保留我的ajax调用。 The success callback invokes the dispatcher. 成功回调调用调度程序。 I use react-router, so i could simply go to the login: 我使用react-router,所以我可以直接登录:

var MyActions = {
  doSomething: function () {
    $.post('/projects/new', {

    }).done(function (res) {
      AppDispatcher.handleViewAction({
        actionType: ProjectConstants.PROJECT_CREATE,
        data: res
      });
    }).fail(function (res) {
      AppDispatcher.handleViewAction({
        actionType: ProjectConstants.UNAUTHORIZED
      });
    });
  }
};

In the store, i handle the unauthorized response: 在商店里,我处理未经授权的回复:

var _unAuth = false;

var MyStore = {
  getUnauthorized() {
    return _unAuth;
  },
  setUnauthorized(val) {
    _unAuth = val;
  }
}

AppDispatcher.register(function(payload) {
  var action = payload.action;
  if (action.actionType === ProjectConstants.UNAUTHORIZED) {
    ProjectStore.setUnauthorized(true);
  }
});

Then in the component invoke the redirect since it has react router scope: 然后在组件中调用重定向,因为它具有反应路由器范围:

class MyComponent extends Component {
  _onChange() {
    if (ProjectStore.getUnauthorized()) {
      this.transitionTo('/login');
    }
  }
}

Though if you want to do a typical page redirect, you can invoke window.location.href = '/login'; 虽然如果要进行典型的页面重定向,可以调用window.location.href ='/ login'; inside the action. 在行动里面。

You can abstract it a bit better by putting login state into a separate store. 您可以通过将登录状态放入单独的存储中来更好地抽象它。 Which is what i've done in my app. 这是我在我的应用程序中完成的。 I was just trying to keep it simple, reduce number of classes & singletons. 我只是想保持简单,减少课程和单身人数。

Edit To handle all ajax requests: 编辑处理所有ajax请求:

I'd just write a wrapper around my ajax library: 我只是在我的ajax库周围写一个包装器:

var ajax = {
  send: function (url, data, success, fail) {
    $.post(url, data).done(success).fail((jqXHR, textStatus, errorThrown) => {
      if (jqXHR.status === 401) {
        location.href = '/login';
      }
      else {
        fail(jqXHR, textStatus, errorThrown);
      }
    });
  }
}

Invoke that instead of the ajax library directly. 直接调用而不是ajax库。

Something i haven't tried, but you could potentially pass the component this down to the function through your action call. 东西我还没有尝试过,但你可能会通过该组件this通过你的行动呼吁下到功能。 Use that to invoke things like transitionTo but that feels unclean to me. 用它来调用transitionTo东西但对我来说感觉不洁净。

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

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