[英]based on array object key value need to setState
I have React error fields which i will be displaying on the screen.我有 React 错误字段,我将在屏幕上显示。
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.在上述情况下,我有一个字段错误,即商家 ID,然后我需要像下面这样设置状态。
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在上述情况下,我有 2 个字段错误,即商家 ID 和密码,然后我需要像下面这样设置状态
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.在上述情况下,我有 3 个字段错误,即商家 ID、密码和重新密码,然后我需要像下面这样设置状态。
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您可以使用 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);
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.请记住,您需要与 state 属性的大小写保持一致,因为它们区分大小写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.