有没有一种方法可以使通用条件轻松扩展我的步骤?

时间:2020-06-16 11:22:54

标签: javascript reactjs if-statement generics

在React上是新功能,并且有一个项目,我必须在其中完成一个React Joyride漫游到完成的工具中。

目前,我有if条件来检查iam的哪一页,以设置正确的步骤。

if (this.props.location.pathname === '/') {
      steps = []
    } else if (this.props.location.pathname === '/matches/' || this.props.location.pathname === '/matches') {
      if (this.props.firstPartClicked === true) {
        steps = matchSiteStepsOne
      } else if (this.props.secondPartClicked === true) {
        steps = matchSiteStepsTwo
      } else {
        steps = matchSiteSteps
      }
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.endsWith('/edit/') && this.props.location.pathname.match('\\d+')) {
      if (this.props.firstPartClicked === true) {
        steps = matchEditorStepsOne
      } else if (this.props.secondPartClicked === true) {
        steps = matchEditorStepsTwo
      } else {
        steps = matchEditorSteps
      }
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.includes('sequence')) {
      if (this.props.firstPartClicked === true) {
        steps = matchSequenceStepsOne
      } else if (this.props.secondPartClicked === true) {
        steps = matchSequenceStepsTwo
      } else {
        steps = matchSequenceSteps
      }
    } else if (this.props.location.pathname.startsWith('/matches/') && this.props.location.pathname.match('\\d+')) {
      steps = matchSteps
    }

现在我的问题是是否有办法使它更通用,这样我就可以轻松地在不同页面上扩展更多步骤,而无需太多冗余代码?

1 个答案:

答案 0 :(得分:0)

只需查找一次路径名,然后像

一样将其存储在变量中,就可以稍微减少冗余代码。
      pathname = this.props.location.pathname  

这应该使您的if语句更短并且更易于阅读。您还可以在某些情况下对某些代码进行重复数据删除,例如您将matchSiteSteps替换为matchSteps ['Site'],并用如下代码调用了函数三次:

if (this.props.firstPartClicked === true) {
        steps = matchStepsOne[type]
      } else if (this.props.secondPartClicked === true) {
        steps = matchStepsTwo[type]
      } else {
        steps = matchSteps[type]
      }
}