【问题标题】:How to properly initialize a store with the props of a component如何使用组件的道具正确初始化商店
【发布时间】:2016-02-14 03:04:42
【问题描述】:

我对 React/Reflux 比较陌生,如果这是一个愚蠢的问题,请原谅。 我有一个想要在我的应用程序中多次使用的 React 组件。 我想用道具初始化这个组件的状态。 如何使用 Reflux 组件的道具设置商店的初始状态? 我在 ReactJS 文档中读到它可能是一种反模式,但我认为它不是。

我尝试了下面的代码,但由于我在 ComponentDidMount 函数上设置了新状态,因此它渲染了我的组件两次。

我不知道如何在初始化时将组件的 props 传递到我的商店。

父组件:

var ParentComponent = React.createClass({

  render: function(){
    return (
      <div className="parent-component">
        <OrderComponent order={parent.order} />
      </div>
    );
  }
});

我的组件:

var OrderComponent = React.createClass({
  mixins: [Reflux.connect(OrderStore, "order")],

  componentDidMount: function(){
    OrderActions.update(this.props.order);
  },
  ...
  render: function(){
    <div>{this.state.order}</div>
  }
})

我的商店:

var OrderStore = Reflux.createStore({
  listenables: [OrderActions],

  onUpdate: function(order){
    this.update(order);
  },

  ...

  update: function(order){
    this.order = order;
    this.trigger(order);
  }
});

【问题讨论】:

    标签: refluxjs


    【解决方案1】:

    要回答您的问题,在您的商店中您不能触发更新。

    var OrderStore = Reflux.createStore({
      listenables: [OrderActions],
    
      onUpdate: function(order, ignoreTrigger){
        this.order = order;
        if (!ignoreTrigger) {
          this.update(order);
        }
      },
    
      ...
    
      update: function(order){
        this.trigger(order);
      }
    });
    

    你说得对,这绝对是一种反模式。您的商店应自行初始化。我建议在您的商店中使用 init 函数来初始化您的订单,以便您的组件可以根据来自您商店的状态进行更新。

    【讨论】:

      猜你喜欢
      • 2018-07-17
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 2019-08-17
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-29
      相关资源
      最近更新 更多