基于数组的对象键值需要设置State



我有React错误字段,我将在屏幕上显示这些字段。

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

错误字段将是动态的。它可能低于

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

在上面的情况下,我有一个字段错误,那就是merchantID,然后我需要像下面这样设置State。

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

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

在上面的情况下,我有两个字段错误,即merchantID和密码,然后我需要像下面的一样设置State

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个字段错误,分别是merchantID、密码和repassword,然后我需要设置State,如下所示。

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

您可以创建一个具有状态更新的对象,并有条件地填充

// 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);

请记住,您需要与状态属性的大小写保持一致,因为它们是区分大小写的。

最新更新