最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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.

Share Improve this question edited Sep 21, 2015 at 5:09 June asked Sep 21, 2015 at 5:04 JuneJune 2,2174 gold badges25 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

Use Array.prototype.slice:

pop: function() {
  this.setState({
    myStack: this.state.myStack.slice(0, -1)
  });
}
发布评论

评论列表(0)

  1. 暂无评论