Javascript 使用class属性设置React中的初始状态

Javascript 使用class属性设置React中的初始状态,javascript,reactjs,class,state,Javascript,Reactjs,Class,State,我有一个React类组件,它在构造函数调用中具有初始状态对象。我最初只是为this.state分配了一个对象文本,但我需要与类中的其他方法共享初始状态对象以重置组件。将初始状态对象移动为类属性并在构造函数中引用该属性是否正确 class SampleComponent extends Component { constructor() { super(); this.state = this.initialState; } initialState = {

我有一个React类组件,它在构造函数调用中具有初始状态对象。我最初只是为this.state分配了一个对象文本,但我需要与类中的其他方法共享初始状态对象以重置组件。将初始状态对象移动为类属性并在构造函数中引用该属性是否正确

class SampleComponent extends Component {
  constructor() {
    super();

    this.state = this.initialState;
  }

  initialState = {
    property1: "...",
    property2: "..."
  };
}

代码似乎有效,但我不确定这是否正确。

初始状态与类解耦:

const initialState={
财产1:“…”,
财产2:“…”
};
//作为班级
类SampleComponent扩展组件{
状态=初始状态;
...
}
//钩子
功能样本组件(道具){
const[myState,setMyState]=useState(initialState);
...
}

这样,您就避免了以后与此有关的bug。initialState

谢谢您的回复。将该对象移出类是完全有意义的。