React.js + Flux - 正确地在商店中初始化数据对象

时间:2015-03-05 15:27:50

标签: javascript reactjs reactjs-flux react-jsx flux

如何在Flux商店中初始化数据对象?

class MyStore {
   constructor() {
      this.myData = {}; 
      // or
      this.myData = null;
   }

   onReceiveData(data) {
      this.myData = data;
   }
}

在我的React组件中,我正在检查数据是否从服务器加载以呈现子项:

render() {
    // <Child /> has required props in `data` object
    return (
        <div>
            {!this.state.myData ? (
               <div>Loading...</div>
            ) : (
               <Child data={this.state.myData} />
            )}
        </div>
    )
}

2 个答案:

答案 0 :(得分:4)

我使用AppBootstrap.js模块来(1)实例化存储,(2)使用服务器的初始数据调度初始化操作,以及(3)渲染根React组件。

示例:

// AppBootstrap.js

var AppConstants = require('AppConstants');
var AppDispatcher = require('AppDispatcher');
var AppRoot = require('AppRoot.react');
var React = require('React');

require('FriendStore');
require('LoggingStore');
require('MessageStore');

module.exports = (initialData, elem) => {
  AppDispatcher.dispatch({
    type: AppConstants.ActionTypes.INITIALIZE,
    data: initialData
  });
  React.render(<AppRoot />, elem);
};

答案 1 :(得分:1)

视图应始终根据通量结构监听存储数据更改。因此,您的视图不应该检查商店是否有数据。相反,Store应通知视图数据已更改。

示例:

var ActionConstants = require('../constants/action-constants.js');
var AppDispatcher = require('../dispatcher/app-dispatcher.js');
var React = require('react');
var EventEmitter = require('events').EventEmitter;

var MyStore = assign({}, EventEmitter.prototype, {
  items_: [],

  emitChange: function() {
    this.emit(ActionConstants.stores.DATA_CHANGED);
  },

  addChangeListener: function(callback) {
    this.on(ActionConstants.stores.DATA_CHANGED, callback);
  },

  removeChangeListener: function(callback) {
    this.removeListener(ActionConstants.stores.DATA_CHANGED, callback);
  }
});

MyStore.dispatchToken = AppDispatcher.register(function(payload) {
  switch(payload.type) {
    // Handle store initiation on action result received.
    // Also broadcast the data change event to listeners.
    case ActionConstants.MyStoreInit:
      MyStore.init(payload.data);
      MyStore.emitChange();
  }
}