If I have a React component that had a property set on its state:
onClick() { this.setState({ foo: 'bar' }); }
Is it possible to remove "foo"
here from Object.keys(this.state)
?
The replaceState method looks like the obvious method to try but it's since been deprecated.
Unmount a React Node React has a top-level API called unmountComponentAtNode() that removes a component from a specific container. The function unmountComponentAtNode() takes an argument as a container from which the specific component should be removed.
No, you can't. The props of a react component are immutable and are not supposed to be changed by the component. If you need to work with the data locally, you could use the state of the component, or better create a local copy of the prop data.
Prop Changes. It's important to note the difference between changes in state and changes in props. Changes in state and/or props will both trigger a re-render of our React component. However, changes in state can only happen internally due to components changing their own state.
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 ( <div> <div onClick={ this.handleClick.bind(this) }>Remove foo</div> <div>Foo { this.state.foo }</div> <div>Bar { this.state.bar }</div> </div> ); } });
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 ( <div> <div onClick={ this.handleClick }>Remove foo</div> <div>Foo { this.state.data.foo }</div> <div>Bar { this.state.data.bar }</div> </div> ); } }); ReactDOM.render(<Hello />, document.getElementById('container'))
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="container"></div>
var Hello = React.createClass({ getInitialState: function () { return { foo: 10, bar: 10 } }, handleClick: function () { let state = {...this.state}; delete state.foo; this.setState(state); }, render: function() { return ( <div> <div onClick={ this.handleClick.bind(this) }>Remove foo</div> <div>Foo { this.state.foo }</div> <div>Bar { this.state.bar }</div> </div> ); }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With