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

后端 未结 10 1991
南笙
南笙 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:29

    I think this is a nice way to go about it =>

    //in constructor
    let state = { 
       sampleObject: {0: a, 1: b, 2: c }
    }
    
    //method
    removeObjectFromState = (objectKey) => {
       let reducedObject = {}
       Object.keys(this.state.sampleObject).map((key) => {
          if(key !== objectKey) reducedObject[key] = this.state.sampleObject[key];
       })
       this.setState({ sampleObject: reducedObject });
    }
    

提交回复
热议问题