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

gub*_*ips 2 javascript state class reactjs

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

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

    this.state = this.initialState;
  }

  initialState = {
    property1: "...",
    property2: "..."
  };
}
Run Code Online (Sandbox Code Playgroud)

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

Den*_*ash 5

initialState从类中解耦:

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

// As Class
class SampleComponent extends Component {
  state = initialState;
  ...
}

// Hooks
function SampleComponent(props) {
  const [myState, setMyState] = useState(initialState);
  ...
}
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以避免将来出现关于this.initialState.