javascript - 从嵌套数组中删除特定项目并保存结果,如何使此代码更清晰

标签 javascript reactjs

我写了这段代码,我知道我要删除的特定项目 (timeslot) 以及该特定项目所属的公司 (name)

我的数据是这样的:

this.state.data = [
  {name: :name1', times: [timeslot1, timeslot2, timeslot3]},
  {name: :name2', times: [timeslot1, timeslot2, timeslot3]},
  {name: :name3', times: [timeslot1, timeslot2, timeslot3]},
]

有没有办法让这段代码更简洁?我觉得它有点冗长或多余:

  deleteTime (timeslot, name) {
    const newState = this.state.data.map(company => {
      if (name === company.name) {
        let newTimes = company.times.filter(time => {
          return time.dateUTCString !== timeslot.dateUTCString
        })
        company.times = newTimes
        return company
      }
      return company
    })
     this.setState({data: newState}) 
  }

最佳答案

你不应该在 map 功能中改变公司,如果你优化你的应用程序并使用 Pure 组件(从 PureComponent 扩展或使用 react.memo),那么当你改变变化时你的组件将不会重新呈现。

这里是你如何用更短的方式写出你所做的事情并且没有变化:

//destructure dateUTCString as that's all you are using
deleteTime({ dateUTCString }, name) {
  this.setState({
    data: this.state.data.map(company =>
      name === company.name
        ? {
            ...company,//copy company
            times: company.times.filter(//reset times
              time => time.dateUTCString !== dateUTCString
            ),
          }
        : company//return original company
    ),
  });
}

关于javascript - 从嵌套数组中删除特定项目并保存结果,如何使此代码更清晰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58605944/

相关文章:

javascript - 键值对的双数据绑定(bind)对象,用于下拉列表

javascript - Ajax:构建 HTML 与注入(inject) HTML

reactjs - 如何在Github Page中使用环境变量?

javascript - 当字段中有对象时,网格空表

javascript - JavaScript 中的 array.select()

php - 从 div 到 textarea 的内容

javascript - 我可以更改 key 对数据的存储方式以使访问非常高效吗?

javascript - 如何从 react-router 升级到 react-router-dom?

javascript - React Native 交错渲染

reactjs - AWS AppSync react : how to work with "complex" GraphQL schema?