如何在reactjs请求中实现条件?

时间:2017-10-21 11:04:22

标签: javascript reactjs if-statement conditional

我之前有这样的要求:

let data = {

      chartLibraryType : this.state.chartCategory == 'highChart'? "HIGH_CHARTS" : "C3",

    };

现在我需要实现3.随着highcharts和c3我也需要传递d3。

let data = {

      chartLibraryType : if(this.state.chartCategory == 'highChart'){
                            "HIGH_CHARTS"
                        }else if(this.state.chartCategory == 'c3Chart'){
                            "C3"
                        }else if(this.state.chartCategory == 'D3Chart'){
                            "D3"
                            },

    };

当我们有超过2个时,这是实现的方式吗?

2 个答案:

答案 0 :(得分:4)

首先,您可以创建dictionary

let dictionary={
   "highChart" : "HIGH_CHARTS",
   "c3Chart" : "C3",
   "D3Chart" : "D3"
}

然后,您必须使用bracket表示法将状态作为字典的键传递。

let data = {
  chartLibraryType : dictionary[this.state.chartCategory]
}

答案 1 :(得分:0)

您可以使用像si这样的开关:

let data = { chartLibraryType: '' }

switch (this.state.chartCategory) {
  case 'highChart':
    data.chartLibraryType = 'HIGH_CHARTS'
    break
  case 'c3Chart':
    data.chartLibraryType = 'C3'
    break
  case 'D3Chart':
    data.chartLibraryType = 'D3'
    break
  // Add as much `case` as you wish without forgetting the break clause
  // If you'd like to fallback to a default value
  default:
    break
}

我还邀请您查看这些精彩的图书集"You don't know JS"