UseEffect正确读取value,但如果在其他地方访问,value是未定义的



目前在我的react-native项目中有以下代码:

const currUser = useSelector((state) => state.userState);
const {currentUser, listings} = currUser;
const dispatch = useDispatch();
useEffect(() => {
if (!currentUser) {
dispatch(fetchUser());
} else {
console.log('This is the current user');
console.log(currentUser);
}
dispatch(fetchUserListings());
});

,然后在同一函数中有以下代码行:

<Text style={[styles.username, {width: '50%'}]}>
@{currentUser.username}
</Text>

当我运行我的应用程序,我得到一个错误说"currentUser.username"是无效的,因为undefined不是对象,但是我的控制台打印以下输出:

This is the current user
Object {
"email": "test120@gmail.com",
"username": "test13",
}

表示正在执行useEffect中的代码,并填充currentUser。我真的很困惑,为什么我能够访问currentUser的值在useEffect中,但是我不能做同样的在useEffect之外。

发生的事情实际上是currentUser的值第一次是undefined,直到API调用执行并且值被设置。您登录useEffect的值是在获取值之后,但错误发生在此之前。

如果我们这样做(如果未定义就赋值一个空对象)

const {currentUser = {}, listings} = currUser;

它不会给你错误。

最新更新