Reactjs:删除数组元素,元素状态不遵循

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

不确定如何在标题中正确地说出这个问题。

场景:React app显示3个元素(下拉列表)的数组,默认情况下已关闭。

I open the second dropdown:
0: state.isOpen: closed
1: state.isOpen: open
2: state.isOpen: closed

I remove the FIRST element of the array:
0: state.isOpen: closed
1: state.isOpen: open

很奇怪,因为我希望新的第一个元素是开放的,第二个元素是关闭的。看起来状态不遵循元素(例如,第二元素状态将在移除后进入新的第二元素状态)。我尝试不改变数组,而是创建一个新的并使用它来设置状态,但结果相同。

我希望新的[0]打开,[1]关闭。我怎么做?谢谢。

//Accounts.js:
accounts.map( () => { return <Account/>})
removeAccount = () => {
    let accounts = this.state.accounts.map(item => return item)
    accounts.splice...
    this.setState({accounts: accounts})
}

//Account.js:
state.isOpen
removeAccount = this.props.removeAccount
javascript arrays reactjs state
2个回答
1
投票

我认为你没有正确克隆你的数组:

removeAccount = () => {
    let accounts = [...this.state.accounts]; // Cloning first
    accounts = accounts.map(item => return item) // Do your mappings here
    accounts.splice... // Do your modifications here
    this.setState({accounts: accounts}); // Set the new state 
}

1
投票

你可以利用Array.prototype.slice() return一个全新的array,排除你的first element而不触及其他任何东西。

请参阅下面的实际示例。

removeAccount = () => {
  return this.setState((state) => {accounts: [...state.accounts.slice(1)]})
}
© www.soinside.com 2019 - 2024. All rights reserved.