首页 > 解决方案 > 为什么我们使用 this.initialState = this.state;

问题描述

谁能向我解释一下为什么要this.initialState知道我在 React JS 中使用了类组件?

class Inscription extends Component {
  constructor(props) {
    super(props);

    this.state = {
      pseudo: '',
      email: '',
      password: '',

      formErrors: {}
    };

    this.initialState = this.state;

  }

标签: javascriptreactjs

解决方案


想象一下有一个包含多个输入的表单,最终用户提交了所有数据。成功提交后,您要重置表单中的所有内容。最简单的方法是这样做this.state = this.initialState,您不需要定义 initialState 两次。

我不会将 initialState 添加到 Class 本身,而是在类之外定义它。

const initialState = {
  pseudo: '',
  email: '',
  password: '',
  formErrors: {}
};

class Inscription extends Component {
  constructor(props) {
    super(props);
    this.state = initialState;
  }
  onSubmit(){
    // do backend call
    // some others events
    // eventually reset the state
    this.state = initialState;
  }
}

推荐阅读