2017-07-25 38 views
0

JavaScript新手,只需要一些幫助,使這更幹。不知道,如果使用switch語句是要走的路...如何讓這個更幹DRY

.catch((err) => { 
    console.log(err) 
    let emailDup = 'user already exists' 
    let userDup = 'username already exists' 
    if (err.response.body.includes(emailDup)) { 
    this.setState({ 
     errMessage: errEmailDup, 
     error: true, 
     loading: false 
    }) 
    } else if (err.response.body.includes(userDup)) { 
    this.setState({ 
     errMessage: errUserDup, 
     error: true, 
     loading: false 
    }) 
    } else { 
    this.setState({ 
     errMessage: errDefault, 
     error: true, 
     loading: false 
    }) 
    } 
} 
+0

現在看起來溼嗎? –

+0

DRY是什麼意思? –

+0

@JenniferGoncalves「不要重複自己」。 – Teemu

回答

3

下面的代碼易於閱讀和維護(添加更多的情況下是很容易以及):

.catch((err) => { 
    let emailDup = 'user already exists'; 
    let userDup = 'username already exists'; 
    let errMessage; 

    if (err.response.body.includes(emailDup)) { 
     errMessage = errEmailDup; 

    } else if (err.response.body.includes(userDup)) { 
     errMessage = errUserDup; 

    } else { 
     errMessage = errDefault; 
    } 

    this.setState({ 
     errMessage: errMessage, 
     error: true, 
     loading: false 
    }); 
} 
2

您可以使用三元

.catch((err) => { 
    let emailDup = 'user already exists' 
    let userDup = 'username already exists' 
     this.setState({ 
      errMessage: err.response.body.includes(emailDup) ? errEmailDup : (err.response.body.includes(userDup) ? errUserDup : errDefault), 
      error: true, 
      loading: false 
     }) 
    } 
+0

謝謝!不過,爲了便於閱讀,這也是可行的,因爲我必須添加其他錯誤消息,@ninjin的解決方案效果更好。 – pitchdiesel