【问题标题】:Flux pattern to initialize Store用于初始化 Store 的通量模式
【发布时间】:2015-06-03 17:48:12
【问题描述】:

大家早上好!

我有一个依赖于 Store 的 React 组件(视图),而 Store 又依赖于从往返到服务器的过程中提取一些状态。

我希望了解的是是否有一个通用模式可以解决初始化 Store 的状态。

现在我想我会做这样的事情:

var SomeView = React.createClass({
  componentWillMount: function() {
    SomeStore.addChangeListener(this._onChange);

    // Go and tell this thing we want to initiliaze our
    // state ahead of time. My worry here is obviously 
    // that when state is updated this fires again so I'd
    // need to have some knowledge that the store has been
    // initialized which seems very (very) kludgey
    SomeActions.init();
  },

  render: function() {
    // Here i'd want to see if I had items available for
    // rendering. If I didn't I'd drop on a loading dialog
    // or if I did I could render the detail.
  },

  _onChange: function() {
     // this.setState...
  }
});


var SomeActions = {
  init: function() {
    AppDispatcher.dispatch({
      actionType: SomeConstants.INIT
    });
  }
};


var SomeStore = assign({}, EventEmitter.prototype, { 
  init: function() {
    $.get('/round/trip', function(data) {
      this.emitChange();
    }).bind(this);
  }

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  }
});


AppDispatcher.register(function(action) {
  switch(action.actionType) {
    case SomeConstants.INIT:
      SomeStore.init()
      break;

    default:
  }
});

我绝对肯定会有更好的方法。

【问题讨论】:

    标签: reactjs reactjs-flux


    【解决方案1】:

    我担心的是,当状态更新时,它会再次触发

    componentWillMount 一旦组件注入 DOM 就会触发,状态更新不会触发此方法。但是,如果您从 DOM 中移除组件(例如:根据某些条件不在父组件中渲染它)并稍后渲染它,该方法将再次被触发。所以init会在商店里被多次调用。

    我相信您应该将 http 请求代码移动到 Web API 模块并从 componentWillMount 方法向 API 触发一个操作,然后 API 将触发 store 并在组件上触发 change 事件,这将更新状态并重新渲染。这就是 Flux 的工作原理。

    如果您只需要获取一次数据并且您知道您的组件将多次从 DOM 中删除/添加到 DOM,您应该将 api 调用放入树中的上层组件(表示入口点的组件到小部件或其他东西)。

    我建议检查Component Container 或高阶组件模式,它基本上将瘦包装器组件定义为视图组件之上的数据层。因此,您可以将视图与数据层完全分开,并且效果很好。

    您可能还想检查另一种方法,来自 ClojureScript 的 Om,它具有单个不可变状态。这进一步简化了一切,实际上是我为自己找到的使用 React 构建应用程序的最佳方式。我为它创建了a starter kit,自述文件中对主要概念有很好的解释。

    【讨论】:

    • 谢谢@Roman - 你能解释一下'API 将触发商店'。我可以向 Web Api 模块触发操作,然后在完成往返后将结果发布回商店,然后让商店发出更改?
    • @Cory 没错。请记住,api 也应该通过操作更新商店。
    • 罗杰。感谢您的提示和链接。今晚我会试一试。
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多