使用唯一ID从状态中的数组中删除对象

问题描述 投票:0回答:2

我列出了哪些元素必须是可删除的(例如使用删除按钮)。我怎么能从反应中意识到这一点?

这是我的状态:

state = {
        infos: [
            {
                id: 1,
                info: 'some info',
                deleted: false
            },
            {
                id: 2,
                info: 'some info',
                deleted: false
            },
            {
                id: 3,
                info: 'some info',
                deleted: false
            }
        ]
    }

这是我尝试删除的功能:

removeInfo() {
  this.state.infos.splice(key, 0)
}

这是我在映射后得到的一个jsx代码:

{
                      this.state.infos.map((item, key) => {
                          return (
                              <ListItem key={item.key + key}>
                                  <Icon color="gray" f7="home" />
                                  <span className="text-black">{item.info}</span>
                                  <Button><Icon f7="edit" color="#39b549" /></Button>
                                  <Button onClick={this.removeInfo}><Icon color="black" f7="trash" /></Button>
                              </ListItem>
                          )
                      })
                  }
javascript arrays reactjs object html-framework-7
2个回答
2
投票

你需要做一些改变。

首先,我们需要将要删除的项的id传递给remove函数:

 <Button onClick={()=>this.removeInfo(item.id)}><Icon color="black" f7="trash" /></Button>

然后,您需要使用setState以不可变的方式从数组中删除该项。

removeInfo(id) {
  this.setState(ps=>({infos:ps.infos.filter(x=>x.id!=id)}))
}

splice改变阵列。


1
投票

您需要使用setState并注意您不能改变状态,因此您需要使用spread运算符来创建新数组。

function removeInfo(index) {
  this.setState((prev) => ({
    infos: [...prev.infos.slice(0, index), ...prev.infos.slice(index+1)]
  }))
}
© www.soinside.com 2019 - 2024. All rights reserved.