在React + ES6中重置初始状态

时间:2017-07-19 20:36:05

标签: javascript reactjs ecmascript-6

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

我在这个课程中有一些我没有提供的功能但改变了titlesizecolor的状态。

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

4 个答案:

答案 0 :(得分:15)

您可以使用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);
  }
}

或只是一个变量:

constructor(props) {
  super(props);

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

答案 1 :(得分:3)

使用建议的类字段,您可以执行以下操作:

class ElementBuilder extends Component {
    static initialState = {
        title: 'Testing,
        size: 100,
        color: '#4d96ce'
    }

    constructor(props) {
        super(props)

        this.state = ElementBuilder.initialState
    }

    resetBuilder() {
        this.setState(ElementBuilder.initialState)
    }
}

答案 2 :(得分:2)

由于初始状态似乎不依赖于任何特定的实例,只需在类外定义值:

const initialState = {...};

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

        this.state = initialState;
    }

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

答案 3 :(得分:0)

使用高阶组件清除组件状态(重新渲染)

例子Element.jsx:

// Target ----- //

class Element extends Component {

  constructor(props){
    super(props)
    const {
        initState = {}
    } = props
    this.state = {initState}
  }

  render() {
    return (
        <div className="element-x">
            {...}
        </div>
    )
  }
}

// Target Manager ----- //

class ElementMgr extends Component {

    constructor(props){
        super(props)
        const {
            hash = 0
        } = props
        this.state = {
            hash, // hash is a post.id 
            load: false
        }
    }

    render() {
        const {load} = this.state
        if (load) {
            return (<div className="element-x"/>)
        } else {
            return (<Element {...this.props}/>)
        }
    }

    componentWillReceiveProps(nextProps) {
        const {hash = 0} = nextProps
        if (hash !== this.state.hash) {
            this.setState({load:true})
            setTimeout(() => this.setState({
                hash,
                load:false
            }),0)
        }
    }
}

export default ElementMgr
相关问题