根据React JS中的其他操作结果调用其他操作

时间:2015-02-23 12:24:38

标签: reactjs reactjs-flux

我有一个PageComponent它包含以下反应组件: -

  1. 添加项目表单。 [FormComponent]
  2. Paginated项目清单。 [UserListComponent]
  3. 当用户点击添加项目表单中的添加项目时。使用ActionCreator调用操作,然后调用API服务器以及成功/失败回调。

    //Calling action action creator from the component
    ActionCreator.addUser({email:email, dept_code:dept});
    
    
    //Action Creator calling action using dispatcher.
    addUser: function(userObj){
      ApiClient.addUser(
        userObj,
        function(response){
           AppDispatcher.handleServerAction({actionType:ActionTypes.ADD_USER_SUCCESS, response: response});
        }.bind(this),
        function(error){
           AppDispatcher.handleServerAction({actionType:ActionTypes.ADD_USER_FAIL, error: error});
        }.bind(this)
      );
    }
    

    当调用成功/失败回调时,它会调度一个动作,例如ADD_USERS_SUCCESS。

    我已将PageStore配置为侦听此操作并通知用户表单已提交。

      dispatcherIndex: AppDispatcher.register(function(payload) {
          var action = payload.action;
          switch(action.actionType){
             case ActionTypes.LOAD_USERS_SUCCESS:
                persistStoreData(false, null, action.usersObj);
                break;
             case ActionTypes.LOAD_USERS_FAIL:
                persistStoreData(false, payload.action.error, {});
                break;
             case ActionTypes.ADD_USER_SUCCESS:
                updateAddFormData(false, "Added", "success", []);
                break;
             case ActionTypes.ADD_USER_FAIL:
                updateAddFormData(true, "Add Failed! Click to retry..", "danger", payload.action.error);
                break;
             default:
                return true;
          }
          UsersStore.emitChange();
          return true; // No errors. Needed by promise in Flux Dispatcher.
     })
    

    问题是如果触发了ADD_USERS_SUCCESS操作,如何更新我的UserListComponent。

    我有以下解决方案: -

    1. 触发一个动作(例如,LOAD_USERS),它会在我的渲染方法上列出用户,例如,如果我在我的状态中有一个标志,如{reloadUserTable:true}?

    2. 在渲染方法中更新状态,但根据Facebook文档在渲染方法中更新状态是AntiPattern。

4 个答案:

答案 0 :(得分:1)

你可以在PageComponent中维护状态,让它的'children'(UserListComponent)使用props属性访问它。

var PageComponent = React.createClass({
         getUserState: function() {
            return {
                allUsers: UsersStore.getAllUsers()
            }
         },
         getInitialState: function() {
            return getUserState();
         },
         /* at ADD_USERS_SUCCESS */
         onChange: function() {
            this.setState(getUserState());
         },
         render: function() {
            <FormComponent />
            {/* inside UserListComponent, access all users using this.props.users */}
            <UserListComponent users={this.state.allUsers} />
         }});

答案 1 :(得分:0)

如果您的PageStore包含对链接到UserListComponent组件的页面的引用,那么在成功时您可以添加到该引用并发出更改。

答案 2 :(得分:0)

只需在子组件上公开一个方法,以便父级调用 - http://facebook.github.io/react/tips/expose-component-functions.html

答案 3 :(得分:0)

解决此问题的解决方案如下所示。 @oppo给出的解决方案中的_onChange回调帮助了我。

我为解决这个问题做了什么: - 1.当调用添加用户操作时,我在我的商店设置了一个标志,如{reloadUsers:true} 2.如果该标志为true,则查看Component的_onChange回调检查,然后触发从API服务器加载数据的操作。

以下是商店

'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher');
var Constants = require('../constants/Constants');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');

var ActionTypes = Constants.ActionTypes;
var CHANGE_EVENT = 'change';
var _state = {
               loading: false,
               error : null,
               users: {},
               isAdded: true,
               addFormErrors: [],
               reloadUsers: false //Whether to reload user table or not
            };
//Stores data recieved from server on page load
function persistStoreData(loading, error, response) {
   _state.loading = loading;
   _state.error = error;
   _state.users = response;
   _state.reloadUsers = false;
}

//Updates data recieved from server if data saved
function updateAddFormData(enableSave){
   _state.enableAddButton = enableSave;
   if(!_state.enableAddButton){
      _state.isAdded = true;
      _state.reloadUsers = true;
   }
   else{
      _state.isAdded = false;
   }
}

var UsersStore = assign({}, EventEmitter.prototype, {
   getState: function(){
      return _state;
   },

   getUsers: function(){
      return this._users;
   },

   emitChange: function() {
    //console.log('store change event');
    this.emit(CHANGE_EVENT);
   },

   /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },

  dispatcherIndex: AppDispatcher.register(function(payload) {
      var action = payload.action;
      switch(action.actionType){
         case ActionTypes.LOAD_USERS_SUCCESS:
            persistStoreData(false, null, action.usersObj);
            break;
         case ActionTypes.LOAD_USERS_FAIL:
            persistStoreData(false, payload.action.error, {});
            break;
         case ActionTypes.ADD_USER_SUCCESS:
            updateAddFormData(false, "Added", "success", []);
            break;
         case ActionTypes.ADD_USER_FAIL:
            updateAddFormData(true, payload.action.error);
            break;
         default:
            return true;
      }
      UsersStore.emitChange();
      return true; // No errors. Needed by promise in Flux Dispatcher.
 })

});
module.exports = UsersStore;

以下是调度员

'use strict';
var Constants = require('../constants/Constants');
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');

var PayloadSources = Constants.PayloadSources;

var AppDispatcher = assign(new Dispatcher(), {

  /**
   * @param {object} action The details of the action, including the action's
   * type and additional data coming from the server.
   */
  handleServerAction: function(action) {
    var payload = {
      source: PayloadSources.SERVER_ACTION,
      action: action
    };
    this.dispatch(payload);
  }

});

module.exports = AppDispatcher;

以下是我的常数

var keyMirror = require('keymirror');

module.exports = {
   ActionTypes: keyMirror({
      ADD_USER_SUCCESS: null,
      ADD_USER_FAIL: null,

      LOAD_USERS: null,
      LOAD_USERS_SUCCESS: null,
      LOAD_USERS_FAIL: null,
   }),
   PayloadSources: keyMirror({
      SERVER_ACTION: null,
   })
};

以下是行动创建者

'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher');
var Constants = require('../constants/Constants');
var ApiClient = require('../clients/ApiClient');
var ActionTypes = Constants.ActionTypes;

var ActionCreator = {

  loadUsers: function(){
     ApiClient.getUsers(function(usersObj) {
       AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_USERS_SUCCESS, usersObj: usersObj});
     }.bind(this), function(error) {
      AppDispatcher.handleServerAction({actionType:ActionTypes.LOAD_USERS_FAIL, error: error});
     }.bind(this));
   }

    addUser: function(userObj){
      ApiClient.addUser(
        userObj,
        function(response){
           AppDispatcher.handleServerAction({actionType:ActionTypes.ADD_USER_SUCCESS, response: response});
        }.bind(this),
        function(error){
           AppDispatcher.handleServerAction({actionType:ActionTypes.ADD_USER_FAIL, error: error});
        }.bind(this)
      );
    }
};
module.exports = ActionCreator;

以下是视图组件的主要部分(仅限重要部分)

'use strict';
var React = require('react');
var ActionCreator = require('../actions/ActionCreator');
var UsersStore = require('../stores/UsersStore');
var UsersTable = require('./UsersTable.jsx');
var UserAddForm = require('./UserAddForm.jsx');
var ManageUsers = React.createClass({

  getInitialState: function() {
      return UsersStore.getState();
  },

  componentDidMount: function() {
      ActionCreator.loadUsers();//Invoking Action, loading initial data
      UsersStore.addChangeListener(this._onChange);
  },

  componentWillUnmount: function() {
     UsersStore.removeChangeListener(this._onChange);
  },

  _onChange: function() {
     var state = UsersStore.getState();
     if(state.reloadUsers === true){
       //Only reload users if state has this variable set
       ActionCreator.loadUsers();
     }
     else{
       this.setState(state);
     }
  },
  render: function(){
    //Rendering logic would go here, below is just a prototype
    return (
       <div>
       <UserAddForm onSubmit={handleFormSubmit} />
       <UsersTable/>
       </div>
    );
  }
});

module.exports = ManageUsers;

以下是API客户端

'use strict';
var $ = require('jquery');
var ApiClient = {

   getUsers : function(success, failure){
      $.ajax({
         url : '/api/get-users',
         dataType: 'json',
         success : function(data){
            success(data);
         },
         error : function(jqXHR, textStatus, errorThrown){
            failure(errorThrown);
         }
      });
   },

   addUser : function(data, success, failure){
      $.ajax({
         url : '/api/add-user',
         dataType: 'json',
         type: 'post',
         data: 'data='+JSON.stringify(data),
         success : function(data){
            success(data);
         },
         error : function(jqXHR){
            var errorObj = {};
            try{
              errorObj = JSON.parse(jqXHR.responseText);
            }
            catch(e){
              errorObj['main'] = "An error occured";
            }
            failure(errorObj);
         }
      });
   }
};
module.exports = ApiClient;