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

Is there a way to create a generic approach to reduce amount of code for similar operations on state?

我是 JS/React/Redux 的初学者。是否有 dynamic/parametric 方法来调用带参数的类似方法而不是重复代码?

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# 中,我会使用没有类型对象的泛型方法来设置它,但我想知道这在 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
  });
}