设置嵌套数组的状态 [英] Set state of nested array

查看:57
本文介绍了设置嵌套数组的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上了这个课:

class Board {
    this.state = {
        lists : [{
            id: 0, 
            title: 'To Do',
            cards : [{id : 0}]
        }]
    }

,并且要在列表"状态数组内的卡"数组上使用setState.以前,我在子组件中拥有纸牌阵列,但现在将其移至Board类.这是我以前拥有的功能.

And want to use setState on the 'cards' array inside of the 'lists' state array. Previously, I had the cards array in a child component but I have now moved it up to the Board class. This is the function that I had before.

deleteCards(id){
    this.setState({
        cards: this.state.cards.filter(card => card.id !== id)
    });
}

我如何更改它,使其在卡位于另一个阵列中时可以正常工作?

How can I change it so that it works now that cards is inside another array?

通过查看这些帖子,我无法解决它:

I was unable to solve it looking at these posts:

ReactJS-数组中对象键的setState

如何在状态数组中编辑项目?

推荐答案

要在 setState 中完成所有操作(请注意, setState 的第一个参数是更新程序函数,其中第一个参数是对先前状态的引用):

To do it all within setState (note that the first argument to setState is an updater function where its first argument is a reference to the previous state):

如果您可以提供呼叫者的 listId :

If you can provide the listId from the caller:

deleteCards(listId, cardId) {
  this.setState(prevState => ({
    lists: prevState.lists.map((list) => {
      if (list.id !== listId) {
        return list
      }

      return {
        ...list,
        cards: list.cards.filter(card => card.id !== cardId) 
      }
    })
  }))
}

如果您不能不能提供呼叫者的 listId :

If you can not provide the listId from the caller:

deleteCards(id) {
  this.setState(prevState => ({
    lists: prevState.lists.map((list) => {
      if (list.cards.some(card => card.id === id)) {
        return {
          ...list,
          cards: list.cards.filter(card => card.id !== id) 
        }
      }

      return list
    })
  }))
}

这篇关于设置嵌套数组的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆