[英]Undefined function in React
I am having an error: Cannot read properties of undefined reading((Id))
.我有一个错误:
Cannot read properties of undefined reading((Id))
。
const PostWidget = ({
postId,
postUserId,
name,
description,
location,
picturePath,
userPicturePath,
likes,
comments,
}) => {
const [isComments, setIsComments] = useState(false);
const dispatch = useDispatch();
const token = useSelector((state) => state.token);
const loggedInUserId = useSelector((state) => state.user._id);
const isLiked = Boolean(likes[loggedInUserId]);
const likeCount = Object.keys(likes).length;
const { palette } = useTheme();
const main = palette.neutral.main;
const primary = palette.primary.main;
const patchLike = async () => {
const response = await fetch(`http://localhost:3001/posts/${postId}/like`, {
method: "PATCH",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ userId: loggedInUserId }),
});
const updatedPost = await response.json();
dispatch(setPost({ post: updatedPost }));
};
The error is generated from const isLiked = Boolean(likes[loggedInUsrId])
which checks for a truthy value if an array of userId liked a post before it gets rendered on the home page.该错误由
const isLiked = Boolean(likes[loggedInUsrId])
生成,如果 userId 数组在帖子呈现在主页上之前点赞该帖子,它会检查真实值。
I expected it to show my homepage and its corresponding output/logic but instead got this from my developer console:我希望它显示我的主页及其相应的输出/逻辑,但却是从我的开发者控制台得到的:
the error is occurring because you are checking for a truthy value on an array of user ids, by using an index which also consists of the userId.发生错误是因为您正在通过使用也由 userId 组成的索引来检查用户 id 数组的真值。
Imagine you have three likes as follows:想象一下,您有以下三个赞:
const likes = ["user1Id", "user2Id", "user3Id"];
now if the logged in user is user1
, when you write:现在如果登录用户是
user1
,当你写:
const isLiked = Boolean(likes[loggedInUserId]);
it is effectively Boolean(likes["user1Id"]).
它实际上是
Boolean(likes["user1Id"]).
Of course, this index does not exist, you only have three indices, 0
, 1
and 2
.当然,这个索引不存在,你只有三个索引,
0
, 1
和2
。
What you could do is try to find the userId in the array, and if it exists then its truthy, if not, it's falsy, like:你可以做的是尝试在数组中找到 userId,如果它存在那么它是真的,如果不存在,它就是假的,比如:
const isLiked = likes.find((userId) => userId === loggedInUserId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.