Let's say I have an react ponent 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 bees annoying when I write these codes.
Is there any nice way for popping from an array type react ponent 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.
Let's say I have an react ponent 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 bees annoying when I write these codes.
Is there any nice way for popping from an array type react ponent 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.
1 Answer
Reset to default 7Use Array.prototype.slice
:
pop: function() {
this.setState({
myStack: this.state.myStack.slice(0, -1)
});
}