我只是在相当简单的任务上遇到了一点困难。如果这个问题已经得到解答,请提前道歉。我就是找不到它。我得到了处于状态的对象
state = {
controls: {
email: {
elementConfig: {
type: 'email'
},
placeholder: 'Email Address',
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false,
errorMsg: ""
},
password: {
elementConfig: {
type: 'password'
},
placeholder: 'Password',
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false,
errorMsg: ""
}
},
};
只有当对象中的“valid”等于 false 时,我才需要将“touched”更新为 true,将“errorMsg”更新为文本
我设法过滤了“有效”值等于 false 的所有对象键
const invalidInputs = Object.keys(this.state.controls).filter(key => {
return this.state.controls[key].valid === false
})
现在我需要循环遍历每个“invalidInputs”并将touched更新为true并将“errorMsg”更新为特定文本。我已经尝试过了
for (let key in invalidInputs){
const updatedControl = {
...this.state.controls,
[invalidInputs[key]]: {
...this.state.controls[invalidInputs[key]],
touched: true,
errorMsg: errorMsg(this.state.controls[invalidInputs[key]].validation, this.state.controls[invalidInputs[key]].value)
}
};
this.setState({controls:updatedControl})
console.log(updatedControl)
}
但这显然不起作用。谁能给我一些好的解决方案或指导我找到答案?
提前致谢
最佳答案
使用for..in
循环遍历对象并检查valid
的值
let state = {
controls: {
email: {
elementConfig: {
type: 'email'
},
placeholder: 'Email Address',
value: '',
validation: {
required: true,
isEmail: true
},
valid: false,
touched: false,
errorMsg: ""
},
password: {
elementConfig: {
type: 'password'
},
placeholder: 'Password',
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false,
errorMsg: ""
}
},
};
for (let keys in state.controls) {
if (!state.controls[keys].valid) {
state.controls[keys].errorMsg = 'New Msg';
state.controls[keys].touched = true;
}
}
console.log(state)
关于javascript - 更新特定对象中的特定属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124987/