How can I remove an attribute from a Reactjs component's state object

后端 未结 10 2068
南笙
南笙 2020-12-06 09:17

If I have a react component that had a property set on it\'s state:

onClick() {
    this.setState({ foo: \'bar\' });
}

Is it possible to re

10条回答
  •  没有蜡笔的小新
    2020-12-06 09:46

    If the removal is in a function and the key needs to be a variable, try this :

    removekey = (keyname) => {
        let newState = this.state;
        delete newState[keyname];
        this.setState(newState)
        // do not wrap the newState in additional curly braces  
    }
    
    this.removekey('thekey');
    

    Almost the same as steve's answer, but in a function.

提交回复
热议问题