Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to pop from a react component's array-type state attribute?

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.

like image 698
June Avatar asked Sep 21 '15 05:09

June


1 Answers

Use Array.prototype.slice:

pop: function() {
  this.setState({
    myStack: this.state.myStack.slice(0, -1)
  });
}
like image 84
Jordan Running Avatar answered Oct 12 '22 05:10

Jordan Running