有没有办法创建一个通用的方法来减少状态上类似操作的代码量?

问题描述 投票:0回答:2

我是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中?

reactjs dry
2个回答
2
投票

是的。由于唯一的区别是您在状态中访问的对象,您可以将其传入然后干掉代码。

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 });
}

2
投票

我会有一个常用的方法,它将迭代并设置和使用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
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.