我有一个简单/愚蠢的函数,它根据用户与之交互的元素来改变我的状态。我的问题是我为每个组复制了几乎相同的代码。有什么办法可以重构这个吗?
handleRequestDeleteChip = (data, group) => {
// NEED REFACTORING
if (group === "client") {
const updatedSelectedClients = removeItem(this.state.currentJob.selectedClients, data.id);
const updatedJobStatus = {
...this.state.currentJob,
selectedClients: updatedSelectedClients
};
this.setState({currentJob: updatedJobStatus});
} else if (group === "product") {
const updatedSelectedProducts = removeItem(this.state.currentJob.selectedProducts, data.id);
const updatedJobStatus = {
...this.state.currentJob,
selectedProducts: updatedSelectedProducts
};
this.setState({currentJob: updatedJobStatus});
} else if (group === "upload") {
const updatedSelectedUplods = removeItem(this.state.currentJob.selectedUploads, data.id);
const updatedJobStatus = {
...this.state.currentJob,
selectedUploads: updatedSelectedUplods
};
this.setState({currentJob: updatedJobStatus});
}
};
由于“选定”项目与组有 1 对 1 的关系,因此您可以创建一个Map(或字典对象),根据组为您提供正确的项目类型。其余的只是使用项目名称:
注意:地图是静态的,所以它可以移动到方法之外。这样就无需在调用该方法时重新创建它。
const itemToChange = new Map([['client', 'selectedClients'], ['product', 'selectedProducts'], ['upload', 'selectedUploads']]); // external map of options
handleRequestDeleteChip = (data, group) => {
const selected = itemToChange.get(group); // get the item by group
if(!selected) { // if no selected for the group
// handle by returning, throwing error, fallback, etc...
}
const updatedSelected = removeItem(this.state.currentJob[selected], data.id); // use brackets notation to get the item
this.setState({
...this.state.currentJob,
[selected]: updatedSelected // use computerd properties to set the correct type
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句