React native - 通过 action 执行存储方法,同时保留组件的“this”上下文

React native - executing store method via action while retaining `this` context of component

希望此代码示例能够很好地解释我要解决的问题。

/**
 * We happen to be working in React Native here, so fluxible's 
 * connectToStores as well as the implementation of flux-react
 * are non-starters here due to both's peer dependency on
 * react.
 */

// Store.js
var Store = {
  getState: function () {
    var endpoint = '/endpoint';

    var promise = fetch(endpoint)
      .then(response => response.json());

    return Promise.resolve(promise)
      .then((data) => {
        this.setState({
          hasData: true,
          data: data
        });
      })
      .done();
  }
};

module.exports = Store;

// Component.js
var Component = React.createClass({

  getInitialState: function () {
    return {
      hasData: false,
      data: {}
    };
  },

  componentDidUpdate: function () {
    console.log('this.state', this.state);
  },

  componentDidMount: function () {
    /**
     * Rather than directly apply here, possible to wrap the Store somehow
     * so that the Component scope of `this` is applied automatically when
     * calling _any_ of Store's methods?
     *
     * Even better, how to execute an action here that triggers a method in
     * the Store and passes along `this` from the Component as the context.
     */
    Store.getState.apply(this);
  },

  render: function () {
    return (
      <View></View>
    );
  }
});

module.exports = Component;

您通过 'this' 所做的工作应该有效。但是,我建议做类似的事情:

this.setState(Store.getState())

如果你多次重复这个,你可以使用 mixin。在 mixin 中,您的 'this' 是上下文。