简体   繁体   English

我可以发送多个活动事件吗?

[英]Can I send several events on action in flux?

I want to show loader when authentication happens. 我想在身份验证发生时显示加载程序。 I've got sendAuthCredentials action. 我有sendAuthCredentials动作。 On this action I want to do several actions: 对于此操作,我要执行几个操作:

  1. Show Loader 显示加载器
  2. Send auth request to server 发送身份验证请求到服务器
  3. Handle response and inform UserStore is user authenticated or not 处理响应并通知UserStore是否已通过用户身份验证
  4. Hide Loader. 隐藏加载程序。

I've got Loader react component, LoaderStore and LoaderAction for working with component. 我已经有了Loader react组件, LoaderStoreLoaderAction来使用该组件。

So my sendAuthCredentials method looks like: 所以我的sendAuthCredentials方法看起来像:

UserActions = {
/**
 * @param {string} username
 * @param {string} password
 */
  sendAuthCredentials: function(username, password) {
    return Q.all(
      [
        LoaderActions.showLoader(),
        authenticateUser(username, password)
          .then(function( data ) {
            if( data ) {
              AppDispatcher.handleViewAction({
                type: ActionTypes.USER_LOGIN_SUCCESS,
                data: data
              });
              return Q( "succcess" );
            } else {
              AppDispatcher.handleViewAction({
                type: ActionTypes.USER_LOGIN_FAIL
              });
              return Q( "failed" );
            }
          })
      ]
    ).then(LoaderActions.hideLoader);
  }
};

It's works but I'm not sure Is it right way to use Actions in Flux. 它是可行的,但我不确定在Flux中使用Actions是否正确。

Thanks for the answer. 感谢您的回答。

Your solution is fine as it is, but as you mention you are not utilizing the potential in Flux. 您的解决方案固然不错,但是正如您提到的,您没有利用Flux的潜力。 If you utilize Flux you do not need to use promises to keep track of your async calls. 如果您使用Flux,则无需使用Promise来跟踪异步调用。 The numbered list of actions you mention is just a regular Flux data flow. 您提到的操作的编号列表只是常规的Flux数据流。

With Flux you would have a UserStore where you could store if this user was authenticated or not (plus other data you would want to store about a user). 使用Flux,您将拥有一个UserStore,您可以在其中存储是否验证了该用户的身份(以及您想存储的有关该用户的其他数据)。 You could then just prompt the loader until you got an event dispatched from the UserStore telling you that the user is authenticated or not. 然后,您可以提示加载程序,直到从UserStore派发了一个事件,通知您该用户已通过身份验证。

var authenticateUser = function(username) {
  <getRequestToAuthentticationResource>
  .then(function(data){
    <storeDataInUserStore>
    emitAuthenticated();
  })
}
var UserStore = _.extend({}, EventEmitter.prototype, {
  dispatcherIndex: AppDispatcher.register(function(payload) {
  var action = payload;
  switch (action.actionType) {
    case UserConstants.AUTHENTICATE:
      authenticateUser(action.username);
      break;
  }
}

Under is an example of how your app would listen and handle the event. 下面是有关您的应用如何监听和处理事件的示例。 Just to clarify, this is a very simple component. 为了澄清,这是一个非常简单的组件。 You could check the authCode in a better way than with an if-else. 您可以比使用if-else更好的方式检查authCode。

 var YourApp = React.createClass({
  getInitialState: function() {
    return {
       authCode: "loading"
    }
  },

  componentDidMount: function() {
    UserStore.addAuthListener(this._onChange);
  },       

  _onChange: function() {
    setState({
       authCode: UserStore.getAuthCode() //Sucess or fail
    });
  }

  render: function() {
    if(this.state.authCode === "loading"){
      return <load information>
    } else if(this.state.authCode === "success") {
      return <success information>
    } else {
      return <fail>
    }
 }

Then your React-component would just have to see what data it would get and show either the user information, error or the loader. 然后,您的React组件将只需要查看它将获得什么数据并显示用户信息,错误或加载器即可。

Just remember you need an addAuthListener in your store and an emitAuthenticated to make this work. 只需记住,您需要在商店中使用addAuthListener,并需要一个generateAuthenticated来完成这项工作。

Best practice is to do the getRequest where you dispatch the actions, and when that returns you notify the store. 最佳实践是在分派操作的地方执行getRequest,并在返回时通知商店。 However, as seen in the example, you can do it in the store as well. 但是,如示例所示,您也可以在商店中执行此操作。

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

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