【问题标题】:Set state of nested array设置嵌套数组的状态
【发布时间】:2018-12-28 05:07:16
【问题描述】:

我有这门课:

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

并且想在 'lists' 状态数组内的 'cards' 数组上使用 setState。以前,我在子组件中有卡片数组,但现在我已将其移至 Board 类。这是我之前的功能。

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

如果卡片在另一个数组中,我该如何更改它以使其正常工作?

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

ReactJS - setState of Object key in Array

How to edit an item in a state array?

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    您应该尝试使用新的 rest 和 spread 语法...

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    const newListItem = {this.state.lists[0].cards.filter....} 
    
    this.setState({lists: [...this.state.lists.cards, newListItem]})
    

    我会将此作为评论,但它很难阅读。这只是您实际编写过滤器所需的示例。

    【讨论】:

    • 这在 const newListItem 之后返回了“这是一个保留字错误”(我用上面写的过滤器替换了过滤器...)。有解决这个问题的语法吗?
    【解决方案2】:

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

    如果您可以提供来电者的listId

    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

    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
        })
      }))
    }
    

    【讨论】:

    • 使用此函数不会导致错误,但不会导致任何事情发生。 deleteCards 被传递给一个按钮,在该按钮上使用 onClick 调用它。我可以确认该按钮正在工作,因为它写入控制台。
    • 我意识到我假设您要删除的卡的id 与它所在列表的id 相同。您是否也可以为此函数提供列表 ID?如果没有,此函数将不得不遍历每个列表,直到找到具有提供的 id 的卡片。
    • 我已经更新了我的答案以反映这两种可能性。
    • 谢谢我能够通过两个 id 并且它按预期工作。如果我想添加到“卡片”数组中,是否需要“prevState”更新程序功能?如更新 deleteCards 函数并用卡片替换过滤器: list.cards.concat([{id: cID}]) ?我想是的。
    • 在访问setState 中的状态时,通常认为使用对先前状态的引用是最佳实践。另外,我会避免使用 concat 改变 list.card 数组,而是使用扩展运算符 (...),如下所示:cards: [...list.cards, {id: cID}]
    猜你喜欢
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多