如何使用ES6缩短此功能?

1 javascript reactjs

该功能只是我需要实现的逻辑的一小部分,代码变得越来越长,我正在寻找创造性的方式以短格式编写此任务。

if (type === '30d') {
  self.setState({
      startDate: last30d,
      endDate: now
    },
    () => {
      this.fetchPeriod('income');
      this.fetchPeriod('expense');
      this.fetchSettings();
    }
  );
} else if (type === '15d') {
  self.setState({
      startDate: last15d,
      endDate: now
    },
    () => {
      this.fetchPeriod('income');
      this.fetchPeriod('expense');
      this.fetchSettings();
    }
  );
} else if (type === '7d') {
  self.setState({
      startDate: last7d,
      endDate: now
    },
    () => {
      this.fetchPeriod('income');
      this.fetchPeriod('expense');
      this.fetchSettings();
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

一种选择是使其涉及每一个对象typestartDate,然后将它传递到setState

const startDatesByType = {
  '30d': last30d,
  '15d': last15d,
  '7d': last7d,
};
const startDate = startDatesByType[type];
if (startDate) {
  self.setState({ startDate, endDate: now },
    () => {
      this.fetchPeriod('income');
      this.fetchPeriod('expense');
      this.fetchSettings();
    }
  );
}
Run Code Online (Sandbox Code Playgroud)

如果可能的话,您可以考虑更改last30d和相关变量,使其startDatesByType对象中,而不是多个独立变量。