The right way to pop out of the state attribute of an array of a reacting component?

Say I have a 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 this works, but just looking at the code myself becomes annoying when I write these codes.

Is there a good way to pop up from the state of a response component like an array?

I implemented push()as

push: function(a) {
    this.setState({myStack: this.state.myStack.concat([a])});
}

in one line.

I believe there is a good one-liner solution for pop.

+4
source share
1 answer

Use Array.prototype.slice:

pop: function() {
  this.setState({
    myStack: this.state.myStack.slice(0, -1)
  });
}
+5
source

Source: https://habr.com/ru/post/1608262/


All Articles