我写了这段代码,我知道我要删除的特定项目 (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/