我是JS / React / Redux的初学者。是否有动态/参数方法用参数调用类似的方法而不是重复代码?
resetSelectedState() {
const geoElement = Object.assign([], this.state.states); // create new copy to avoid mutation
geoElement.forEach((a) => a.isSelected = false);
this.setState({ states: geoElement });
}
resetSelectedCountry() {
const geoElement = Object.assign([], this.state.countries); // create new copy to avoid mutation
geoElement.forEach((a) => a.isSelected = false);
this.setState({ countries: geoElement });
}
resetSelectedContinent() {
const geoElement = Object.assign([], this.state.continents); // create new copy to avoid mutation
geoElement.forEach((a) => a.isSelected = false);
this.setState({ continents: geoElement });
}
在C#中我会使用带有out类型对象的泛型方法来设置它,但我想知道这是否可以在JS中?
是的。由于唯一的区别是您在状态中访问的对象,您可以将其传入然后干掉代码。
doSomething(type) {
const geoElement = Object.assign([], this.state[type]); // create new copy to avoid mutation
geoElement.forEach((a) => a.isSelected = false);
this.setState({ [type]: geoElement });
}
我会有一个常用的方法,它将迭代并设置和使用computed property name
以避免重复。
resetSelectedState() {
this.reset('states');
}
resetSelectedCountry() {
this.reset('countries');
}
resetSelectedContinent() {
this.reset('continents');
}
reset(property) {
const geoElement = [...this.state[property]];
geoElement.forEach((a) => a.isSelected = false);
this.setState({
[property]: geoElement
});
}