TypeError: Cannot read propertiy of undefined (reading 'includes')
TypeError: Cannot read propertiy of undefined (reading 'includes')
我明白了
TypeError: Cannot read properties of undefined (reading 'includes'),
Line of, "const followed, setFollowed "
这才是真正的问题所在?但我不明白这有什么问题??
const PF = process.env.REACT_APP_PUBLIC_FOLDER;
const [friends, setFriends] = useState([]);
const { user: currentUser, dispatch } = useContext(AuthContext);
const [followed, setFollowed] = useState(
currentUser.followings.includes(user?.id)
);
getFriends();
}, [user]);
const handleClick = async () => {
try {
if (followed) {
await axios.put(`/users/${user._id}/unfollow`, {
userId: currentUser._id,
});
dispatch({ type: "UNFOLLOW", payload: user._id });
} else {
await axios.put(`/users/${user._id}/follow`, {
userId: currentUser._id,
});
dispatch({ type: "FOLLOW", payload: user._id });
}
setFollowed(!followed);
} catch (err) {}
};```
变量 currentUser 没有值 'followings'(因此未定义)
尝试给它一个默认值或使用短路语法,或可选的链接运算符
短路语法
currentUser.followings && currentUser.followings.includes(user?.id)
可选链接
currentUser.followings?.includes(user?.id)
我明白了
TypeError: Cannot read properties of undefined (reading 'includes'),
Line of, "const followed, setFollowed "
这才是真正的问题所在?但我不明白这有什么问题??
const PF = process.env.REACT_APP_PUBLIC_FOLDER;
const [friends, setFriends] = useState([]);
const { user: currentUser, dispatch } = useContext(AuthContext);
const [followed, setFollowed] = useState(
currentUser.followings.includes(user?.id)
);
getFriends();
}, [user]);
const handleClick = async () => {
try {
if (followed) {
await axios.put(`/users/${user._id}/unfollow`, {
userId: currentUser._id,
});
dispatch({ type: "UNFOLLOW", payload: user._id });
} else {
await axios.put(`/users/${user._id}/follow`, {
userId: currentUser._id,
});
dispatch({ type: "FOLLOW", payload: user._id });
}
setFollowed(!followed);
} catch (err) {}
};```
变量 currentUser 没有值 'followings'(因此未定义)
尝试给它一个默认值或使用短路语法,或可选的链接运算符
短路语法
currentUser.followings && currentUser.followings.includes(user?.id)
可选链接
currentUser.followings?.includes(user?.id)