Let's say I have an react component like:
var MyComponent = React.createClass({
getInitialState: function() {
return {
myStack: []
};
},
...
pop: function(a) {
// any concise , elegant way to pop from array type state?
}
}
Maybe I could just write
pop: function() {
var clone = _.clone(this.state.myStack);
clone.pop();
this.setState({myStack: clone});
}
But it looks ugly... I know it works but just looking at the code itself becomes annoying when I write these codes.
Is there any nice way for popping from an array type react component state?
I implemented push()
like
push: function(a) {
this.setState({myStack: this.state.myStack.concat([a])});
}
in a single line.
I believe there is an nice one line solution for pop
, too.
Use Array.prototype.slice
:
pop: function() {
this.setState({
myStack: this.state.myStack.slice(0, -1)
});
}
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