微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 重置React ES6中的初始状态

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

在这个类中有一些我没有提供但是改变标题,大小和颜色状态的函数.

在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() });
    }
}

解决方法

您可以使用getter函数
class ElementBuilder extends Component {
    constructor(props) {
        super(props);

        this.state = this.initialState;
    }

    get initialState() {
      return {
          title: 'Testing',};
    }

    resetBuilder() {
        this.state(this.initialState);
    }
}

或只是一个变量:

constructor(props) {
    super(props);

    this.initialState = {
        title: 'Testing',};
    this.state = this.initialState;
}

原文地址:https://www.jb51.cc/js/149921.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐