Reactjs 有没有一种方法可以创建一种通用方法来减少状态机上类似操作的代码量?

Reactjs 有没有一种方法可以创建一种通用方法来减少状态机上类似操作的代码量?,reactjs,dry,Reactjs,Dry,我是JS/React/Redux的初学者。是否有一种动态/参数化方法来调用具有参数的类似方法,而不是重复代码 resetSelectedState(){ const geoElement=Object.assign([],this.state.states);//创建新副本以避免变异 geoElement.forEach((a)=>a.isSelected=false); this.setState({states:geoElement}); } resetSelectedCountry(){

我是JS/React/Redux的初学者。是否有一种动态/参数化方法来调用具有参数的类似方法,而不是重复代码

resetSelectedState(){
const geoElement=Object.assign([],this.state.states);//创建新副本以避免变异
geoElement.forEach((a)=>a.isSelected=false);
this.setState({states:geoElement});
}
resetSelectedCountry(){
const geoElement=Object.assign([],this.state.countries);//创建新副本以避免变异
geoElement.forEach((a)=>a.isSelected=false);
这个.setState({国家:geoElement});
}
重置所选大陆(){
const geoElement=Object.assign([],this.state.contractions);//创建新副本以避免变异
geoElement.forEach((a)=>a.isSelected=false);
这个.setState({大陆:geoElement});
}

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

是的。因为唯一的区别是您正在访问的对象处于状态,所以您可以将其传入,然后擦干代码

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

我会有一个通用的方法来迭代和设置并使用
计算属性名
,以避免重复

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

我会有一个通用的方法来迭代和设置并使用
计算属性名
,以避免重复

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

谢谢你的解决方案。看起来[type]让生活变得更轻松了谢谢你的解决方案。看起来[类型]让生活变得容易多了