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

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

    You can set foo to undefined, like so

    var Hello = React.createClass({
        getInitialState: function () {
            return {
                foo: 10,
                bar: 10
            }
        },
    
        handleClick: function () {
            this.setState({ foo: undefined });
        },
    
        render: function() {
            return (
                
    Remove foo
    Foo { this.state.foo }
    Bar { this.state.bar }
    ); } });

    Example

    Update

    The previous solution just remove value from foo and key skill exists in state, if you need completely remove key from state, one of possible solution can be setState with one parent key, like so

    var Hello = React.createClass({
      getInitialState: function () {
        return {
          data: {
            foo: 10,
            bar: 10
          }
        }
      },
        	
      handleClick: function () {
        const state = {
          data: _.omit(this.state.data, 'foo')
        };
        
        this.setState(state, () => {
          console.log(this.state);
        });
      },
            
      render: function() {
        return (
          
    Remove foo
    Foo { this.state.data.foo }
    Bar { this.state.data.bar }
    ); } }); ReactDOM.render(, document.getElementById('container'))
    
    
    
    

提交回复
热议问题