我正在尝试检查空值,即使我知道值为null,循环仍然不会中断。为任何帮助干杯
constructor(){
super();
this.state = {
warningMsg: 'No Warnings'
}
this.detail = {
name: null,
phone: null,
email: null,
location: null,
extraDetail: 'Default'
}
}
handleSubmit(){
const {DetailStore} = this.props;
for (let value in this.detail) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({warningMsg:'Check Input'});
break;
}
}
DetailStore.entDetail(this.detail);
console.log(DetailStore.getDetail,'Submitted');
}
答案 0 :(得分:1)
for..in
循环遍历对象的属性名称,而不是属性的值。如果要迭代对象值,最好使用Object.values
代替:
if (Object.values(this.detail).some(value => value === null)) {
console.log('null found');
this.setState({warningMsg:'Check Input'});
}
答案 1 :(得分:1)
'价值'在你的for循环中实际上是属性名称。你需要检查:
if (this.detail[value] === null)
你真正想要的是:
const detailValues = Object.values(this.detail);
for (const value of detailValues) {
console.log(value)
if (value === null) {
console.log('null found'); // i should see this in console but i don't
this.setState({
warningMsg: 'Check Input'
});
break;
}
}