Clearing state es6 React

前端 未结 13 851
独厮守ぢ
独厮守ぢ 2020-12-07 13:04

I am trying to clear a components state but can\'t find a reference for the es6 syntax. I was using:

this.replaceState(this.getInitialState());

13条回答
  •  死守一世寂寞
    2020-12-07 13:46

    In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.

    So, inside constructor you would have:

        class MyComponent extends Component {
            constructor(props) {
                super(props)
                this.state = {
                    key: value,
                    key2: value
                }
                this.initialState = { ...this.state } 
            }
        }
    

    From there you can use

    this.setState(this.initialState);
    

    to reset. But if for some reason your initial state is more complex object, use some library.

提交回复
热议问题