【问题标题】:Reactjs: remove array element, element states don't followReactjs:删除数组元素,元素状态不跟随
【发布时间】:2018-06-01 11:13:53
【问题描述】:

不知道如何在标题中正确表达这个问题。

场景: React 应用显示一个包含 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


【解决方案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 
}

【讨论】:

  • 对不起,我更正了我的代码。我做了 accounts = state.accounts.map... 然后编辑了账户。我仍然得到同样的奇怪行为
  • map 没有克隆数组,我已经编辑了我的答案
【解决方案2】:

您可以利用Array.prototype.slice()return 一个全新的array,它不包括您的first element,而无需触及其他任何东西。

请参阅下面的实际示例。

removeAccount = () => {
  return this.setState((state) => {accounts: [...state.accounts.slice(1)]})
}

【讨论】:

  • 试过了,不能解决问题。我已经确认使用全新的阵列无法解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 2018-02-02
  • 2015-06-14
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-09-29
相关资源
最近更新 更多