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

javascript - Remove first item of array in react state - Stack Overflow

programmeradmin5浏览0评论

I know how to do this but trying this way and not sure why it wont work?

  drawCard = () => {
    const deck = this.state.cards;
    deck.shift();
    console.log(deck, 'deck'); //this is correctly logging one less everytime
    this.setState({cards: deck})
  }

cards is just an of objects

so even though the function is being called and the console log is working, why is it not updating state?

(console.log(state.cards.length) always returns 3)

I know how to do this but trying this way and not sure why it wont work?

  drawCard = () => {
    const deck = this.state.cards;
    deck.shift();
    console.log(deck, 'deck'); //this is correctly logging one less everytime
    this.setState({cards: deck})
  }

cards is just an of objects

so even though the function is being called and the console log is working, why is it not updating state?

(console.log(state.cards.length) always returns 3)

Share Improve this question asked May 3, 2018 at 18:26 The WalrusThe Walrus 1,2087 gold badges31 silver badges49 bronze badges 1
  • 3 You are mutating the state. Try const deck = [...this.state.cards]; – Prakash Sharma Commented May 3, 2018 at 18:30
Add a ment  | 

3 Answers 3

Reset to default 14

Don't use methods that mutate the state (for instance, Array#shift). You could instead use Array#slice to return a shallow copy of a portion of the array:

drawCard = () => {
  this.setState({ cards: this.state.cards.slice(1) })
}

The problem arises because you are directly modifying the state. Although you are assigning the state to 'deck' remember that in Javascript arrays and objects are references. So when you are modifying deck you are actually trying to modify the state itself. You can use other methods to create a copy of the states values and modify that.

You may find this helpful: React - Changing the state without using setState: Must avoid it?

in react, you can't just change the state, you need to create a copy of your state before updating,

the easiest way to do it is just replace this:

 const deck = this.state.cards;

into this:

const deck = [...this.state.cards];
发布评论

评论列表(0)

  1. 暂无评论