簡體   English   中英

我可以發送多個活動事件嗎?

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

我想在身份驗證發生時顯示加載程序。 我有sendAuthCredentials動作。 對於此操作,我要執行幾個操作:

  1. 顯示加載器
  2. 發送身份驗證請求到服務器
  3. 處理響應並通知UserStore是否已通過用戶身份驗證
  4. 隱藏加載程序。

我已經有了Loader react組件, LoaderStoreLoaderAction來使用該組件。

所以我的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);
  }
};

它是可行的,但我不確定在Flux中使用Actions是否正確。

感謝您的回答。

您的解決方案固然不錯,但是正如您提到的,您沒有利用Flux的潛力。 如果您使用Flux,則無需使用Promise來跟蹤異步調用。 您提到的操作的編號列表只是常規的Flux數據流。

使用Flux,您將擁有一個UserStore,您可以在其中存儲是否驗證了該用戶的身份(以及您想存儲的有關該用戶的其他數據)。 然后,您可以提示加載程序,直到從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;
  }
}

下面是有關您的應用如何監聽和處理事件的示例。 為了澄清,這是一個非常簡單的組件。 您可以比使用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>
    }
 }

然后,您的React組件將只需要查看它將獲得什么數據並顯示用戶信息,錯誤或加載器即可。

只需記住,您需要在商店中使用addAuthListener,並需要一個generateAuthenticated來完成這項工作。

最佳實踐是在分派操作的地方執行getRequest,並在返回時通知商店。 但是,如示例所示,您也可以在商店中執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM