使用开关设置状态ReactJS的替代方法

时间:2018-11-28 10:27:09

标签: javascript reactjs switch-statement state

我在React中创建了一个函数来隐藏过滤器。 我在一个容器组件中有多个过滤器组件,每个过滤器组件都有一个相应的状态来添加一个隐藏/显示css类。

我想知道是否有人知道一种更好的方法来对该函数进行编程,因为以这种方式进行编程有点繁琐。

hideFilters(clickedFilter){
  switch(clickedFilter.toLowerCase()){
    case "assortiment":
      this.setState({
          "assortiment": "show",
          "taal":"hide",
          "bestelbaar":"hide",
          "verschijningsjaar":"hide",
          "verschijningsvorm":"hide",
          "nur":"hide"
      });
      break;
    case "bestelbaar":
      this.setState({
          "bestelbaar":"show",
          "assortiment": "hide",
          "taal":"hide",
          "verschijningsjaar":"hide",
          "verschijningsvorm":"hide",
          "nur":"hide"
      });
      break;
    case "taal":
      this.setState({
          "taal":"show",
          "assortiment": "hide",
          "bestelbaar":"hide",
          "verschijningsjaar":"hide",
          "verschijningsvorm":"hide",
          "nur":"hide"
      });
      break;
    case "verschijningsvorm":
      this.setState({
          "verschijningsvorm":"show",
          "assortiment": "hide",
          "bestelbaar":"hide",
          "verschijningsjaar":"hide",
          "taal":"hide",
          "nur":"hide"
      });
      break;
    case "verschijningsjaar":
      this.setState({
          "verschijningsjaar":"show",
          "assortiment": "hide",
          "bestelbaar":"hide",
          "verschijningsvorm":"hide",
          "taal":"hide",
          "nur":"hide"
      });
      break;
    default:  console.log('hi')
  }
}

1 个答案:

答案 0 :(得分:3)

this.defaultStates = {
  "assortiment": "hide",
  "taal":"hide",
  "bestelbaar":"hide",
  "verschijningsjaar":"hide",
  "verschijningsvorm":"hide"
}

hideFilters(clickedFilter){
  this.setState({
    ...this.defaultStates,
    [clickedFilter.toLowerCase()]: "show"
  })
}