在React + ES6中重置初始状态

Zac*_*iro 15 javascript ecmascript-6 reactjs

我在ElementBuilder下面有一个类,当用户保存Element它们已构建时,我希望状态重置为下面的值.

我在这个班,我没有提供而是改变的状态的一些功能title,size以及color.

在ES 5中,我会getInitialState在我的类上有一个函数,可以调用this.getInitialState()函数.

这个元素存在于我的应用程序中,用于登录用户的生命周期,我希望默认值始终相同,无论过去的用法如何.

如何在不编写设置默认值对象的函数(或者可能是答案)的情况下实现此目的?谢谢!

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

        this.state = {
            title: 'Testing,
            size: 100,
            color: '#4d96ce',
        };
    }

    resetBuilder() {
        this.setState({ this.getInitialState() });
    }
}
Run Code Online (Sandbox Code Playgroud)

quo*_*Bro 19

您可以使用getter函数:

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

    this.state = this.initialState;
  }

  get initialState() {
    return {
      title: 'Testing',
      size: 100,
      color: '#4d96ce',
    };
  }

  resetBuilder() {
    this.setState(this.initialState);
  }
}
Run Code Online (Sandbox Code Playgroud)

或只是一个变量:

constructor(props) {
  super(props);

  this.initialState = {
    title: 'Testing',
    size: 100,
    color: '#4d96ce',
  };
  this.state = this.initialState;
}
Run Code Online (Sandbox Code Playgroud)

  • 只是注意,我认为在构造函数中你应该调用this.getInitialState而不是this.initialState,而在getInitialState函数中你应该使用this.setState而不是this.state. (2认同)