不改变状态的React过滤器方法 [英] React filter method without mutating state

查看:77
本文介绍了不改变状态的React过滤器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的状态是:

state = { items : [{id: 1, text: 'test words'}, {id: 2, text: 'another test'}]

这是我的功能,用于从数组中删除对象,从而避免改变状态.

Here's my function to remove objects from the array, trying to avoid mutating state.

handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState(prevState => ({
    items: prevState.items = newArray
  }))

  console.log('handle remove runned', passedInId, myItems, newArray)

}

它工作得很好,但是在继续生活之前想知道它是否不是反模式

It works perfectly but would like to know if it's not anti-pattern before moving on with my life

非常感谢!

推荐答案

您的功能几乎是正确的,并且您有正确的想法.您无需使用您的案例中带有mutator函数的setState版本,只需执行以下操作即可:

Your function is almost right, and you have the right idea. You don't need to use the version of setState that takes a mutator function in your case, instead just do:

handleRemove(passedInId) {

  const myItems = this.state.items

  const newArray = myItems.filter(item => item.id !== passedInId)

  this.setState({
    items: newArray
  })

  console.log('handle remove runned', passedInId, myItems, newArray)

}

说实话,这很简单,一个班轮就能做到:

To be honest, this is simple enough that a one liner will do:

handleRemove(passedInId) {
  this.setState({items: this.state.items.filter(item => item.id !== passedInId)})
}

这篇关于不改变状态的React过滤器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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