我有一个React JS状态对象,并且希望在对象为空时执行一些代码。我的逻辑有什么问题吗?因为if块中的代码没有被执行。
if (this.state.errors == null) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
我有一个React JS状态对象,并且希望在对象为空时执行一些代码。我的逻辑有什么问题吗?因为if块中的代码没有被执行。
if (this.state.errors == null) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
this.state.errors
是一个对象,你可以这样做,//when this.state.errors object is empty
if (Object.keys(this.state.errors).length === 0) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
Object.keys
会返回对象this.state.errors
的所有键的数组。然后,您可以检查该数组的长度来确定它是否为空对象。
this.state
中的内容吗?添加一个调试器并检查它的值。 - Ankit AgarwalObject.keys(this.state.errors).length != 0
而不是!Object.keys(this.state.errors).length == 0
。 - Boommeister实际上,您需要首先检查 this.state.errors
是否存在,然后再检查对象是否为 null
if (this.state.errors && !Object.keys(this.state.errors)) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
if (this.state) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
cheers
if (this.state && !this.state.errors) {
this.props.updateUser(user);
this.props.navigation.goBack();
}
当你在访问另一个对象中的对象值时,你可能需要检查父对象是否存在。如果对象this.state
为null
或undefined
,它会抛出控制台错误。
Uncaught TypeError: Cannot read property 'errors' of undefined
at <anonymous>:1:15
-- 如果是数组
if(!this.state?.example?.length) //ES 6 and above
-- 如果是对象
if(!Object.entries(this.state?.example).length)