使用类属性在 React 中设置初始状态

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


class SampleComponent extends Component {

  constructor() {

    super();


    this.state = this.initialState;

  }


  initialState = {

    property1: "...",

    property2: "..."

  };

}

该代码似乎有效,但我不确定这是否是解决此问题的正确方法。


红糖糍粑
浏览 111回答 1
1回答

慕桂英3389331

initialState从类中解耦:const initialState = {    property1: "...",    property2: "..."};// As Classclass SampleComponent extends Component {  state = initialState;  ...}// Hooksfunction SampleComponent(props) {  const [myState, setMyState] = useState(initialState);  ...}通过这种方式,您可以避免将来出现关于this.initialState.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript