簡體   English   中英

基於數組 object 鍵值需要 setState

[英]based on array object key value need to setState

我有 React 錯誤字段,我將在屏幕上顯示。

this.state = {
    errorMerchantid: '',
    errorPassword: '',
    errorRePassword: '' 
}

錯誤字段將是動態的。 它可能如下所示

err.response.data={
    merchantID: 'merchant id error'
}

在上述情況下,我有一個字段錯誤,即商家 ID,然后我需要像下面這樣設置狀態。

this.setState ({errorMerchantid: err.response.data.merchantID })

或者

err.response.data={
    merchantID: 'merchant id error',
    password: 'invalid password'
}

在上述情況下,我有 2 個字段錯誤,即商家 ID 和密碼,然后我需要像下面這樣設置狀態

 this.setState ({errorMerchantid: err.response.data.merchantID, 
                 errorPassword: err.response.data.errorPassword})

或者

err.response.data={
    merchantID: 'merchant id error',
    password: 'invalid password',
    repassword: 'invalid re-entered password'
}

在上述情況下,我有 3 個字段錯誤,即商家 ID、密碼和重新密碼,然后我需要像下面這樣設置狀態。

 this.setState ({errorMerchantid: err.response.data.merchantID, 
                  errorPassword: err.response.data.errorPassword, 
                  repassword: err.response.data.repassword  })

您可以使用 state 的更新創建 object,並有條件地填充它

 // err.response.data const {merchantID,password,repassword} = err.response.data; const errors = {}; if (merchantID){ errors.errorMerchantid = merchantID; } if (password){ errors.errorPassword = password; } if (merchantID){ errors.errorRePassword = repassword; } this.setState(errors);


如果您每次都需要重置其他錯誤,那么您可以這樣做

 // err.response.data const {merchantID,password,repassword} = err.response.data; const errors = { errorMerchandId: merchantID || '', errorPassword: password || '', errorRePassword: repassword || '' }; this.setState(errors);

請記住,您需要與 state 屬性的大小寫保持一致,因為它們區分大小寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM