I have React error fields which i will be displaying on the screen.
this.state = {
errorMerchantid: '',
errorPassword: '',
errorRePassword: ''
}
error fields will be dynamic. it may have like below
err.response.data={
merchantID: 'merchant id error'
}
in the above case i have one field error which is merchantID, then I need to setState like below.
this.setState ({errorMerchantid: err.response.data.merchantID })
or
err.response.data={
merchantID: 'merchant id error',
password: 'invalid password'
}
in the above case i have 2 fields error which is merchantID and password, then I need to setState like below
this.setState ({errorMerchantid: err.response.data.merchantID,
errorPassword: err.response.data.errorPassword})
or
err.response.data={
merchantID: 'merchant id error',
password: 'invalid password',
repassword: 'invalid re-entered password'
}
in the above case i have 3 fields error which is merchantID, password and repassword, then I need to setState like below.
this.setState ({errorMerchantid: err.response.data.merchantID,
errorPassword: err.response.data.errorPassword,
repassword: err.response.data.repassword })
You can create an object with the updates to the state, and populate it conditionally
// 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);
If you need to reset the other errors each time then you could do
// err.response.data const {merchantID,password,repassword} = err.response.data; const errors = { errorMerchandId: merchantID || '', errorPassword: password || '', errorRePassword: repassword || '' }; this.setState(errors);
Keep in mind that you need to be consistent with the case of the state properties are they are case-sensitive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.