Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我可以在React中使用非纯对象作为状态吗?_Reactjs - Fatal编程技术网

Reactjs 我可以在React中使用非纯对象作为状态吗?

Reactjs 我可以在React中使用非纯对象作为状态吗?,reactjs,Reactjs,我想使用函数实例,而不是纯对象,作为react中的状态对象。但我不确定这是否合适: class Test extends Component { constructor(props) { super(props); this.state = new Domain(); } } 只要typeof new Domain()=“object”就可以了 您必须记住(并且可能要说明)的是,如果实例自身更新,React将不会知道它 对this.state的所有更改都必须通过setS

我想使用函数实例,而不是纯对象,作为react中的状态对象。但我不确定这是否合适:

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = new Domain();
  }
}

只要
typeof new Domain()=“object”
就可以了

您必须记住(并且可能要说明)的是,如果实例自身更新,React将不会知道它

this.state
的所有更改都必须通过
setState
接口,而
函数可能不知道这一点

this.state = new Domain();

// this won't cause your component to re-render
this.state.update(10);

// and this is an anti-pattern
this.setState(this.state);
监听对象的更改是非常困难的,如果域对象具有修改其状态的实例方法,您可能会发现很难将其与组件保持同步。

是的,没关系

javascript中没有纯对象或非纯对象(有纯函数)。但是,有一些方法可以用来创建javascript对象

其中一个是“函数构造函数”,它是您在
newdomain()
中使用的构造函数,另一个常见的构造函数是对象文字符号
{}

React只需要一个对象,他不在乎你用什么符号来创建它