我有一个react状态对象,如果对象是空的,我希望执行一些代码。我的逻辑有什么问题吗?因为if块中的代码没有被执行。
if (this.state.errors == null) {
this.props.updateUser(user);
this.props.navigation.goBack();
}发布于 2018-01-20 06:53:25
考虑到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返回一个数组或所有键。然后,您可以检查该数组的长度,以确定它是否为空对象。
发布于 2018-01-20 06:55:38
实际上,您需要先检查this.state.errors是否存在,然后再检查对象是否为null。
if (this.state.errors && !Object.keys(this.state.errors)) {
this.props.updateUser(user);
this.props.navigation.goBack();
}发布于 2018-01-20 06:54:07
尝试检查状态而不是错误集合:
if (this.state) {
this.props.updateUser(user);
this.props.navigation.goBack();
}干杯
https://stackoverflow.com/questions/48353471
复制相似问题