setState 更改构造函数类型

setState changes constructor type

我发现,当通过 setState 设置 class 实例时,它会失去其构造函数并成为 plain object。我在文档中看到 setState 将值与当前状态合并,可能无法处理复杂类型。那么,状态是否应该始终是普通的内置类型?

http://jsfiddle.net/58c8e7e3/1/

=====代码===

/** @jsx React.DOM */

//===============  transpiled through babeljs.io ======//
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Data = (function () {
    function Data() {
        _classCallCheck(this, Data);
    }

    Data.prototype.isLoading = function isLoading() {
        return this.__state == 2;
    };

    return Data;
})();

//============

var Hello = React.createClass({
  getInitialState: function() {
    return new Data();
  },

  render: function() {
    return (
      <div>
      State: <pre>{JSON.stringify(this.state)} proto: {this.state.constructor.name} </pre>
      <button onClick={this.setXsimple}>setState</button>
      </div>
    );
  },

  setXsimple: function() {
    this.setState(new Data());
  }
});

React.renderComponent(<Hello name="World" />, document.body);

是的,this.state 应该是一个普通的 JavaScript 对象。但是,您可以将复杂类型作为该对象的

/** @jsx React.DOM */

//===============  transpiled through babeljs.io ======//
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Data = (function () {
    function Data() {
        _classCallCheck(this, Data);
    }

    Data.prototype.isLoading = function isLoading() {
        return this.__state == 2;
    };

    return Data;
})();

//============

var Hello = React.createClass({
  getInitialState: function() {
    return { data: new Data() };
  },

  render: function() {
    return (
      <div>
      State: <pre>{JSON.stringify(this.state)} proto: {this.state.data.constructor.name} </pre>
      <button onClick={this.setXsimple}>setState</button>
      </div>
    );
  },

  setXsimple: function() {
    this.setState({ data: new Data() });
  }
});

来自docs

The first argument can be an object (containing zero or more keys to update) or a function (of state and props) that returns an object containing keys to update.

我假设他们在这里指的是普通对象,而不是 类 或数组 f。例如