我正在尝试使用用户ID设置条件逻辑,以便如果通过身份验证的用户与创建此帖子的用户相同,则不要显示“喜欢”按钮。这有效,但是如果用户未登录,则会出现此错误cannot read property '_id' of undefined
。基本上,用户是未定义的,因为在注销用户时未对任何用户进行身份验证,那么如何处理此操作而又不会出现此错误且应用程序崩溃?如何解决此错误,但仍将逻辑与用户ID保持在一起?谢谢
Post.js
...
.then((result) => {
const {
user: { _id },
} = isAuthenticated();
let updatedPost = { ...post };
updatedPost.likes.push(id);
setPost(updatedPost);
})
.catch((err) => {
console.log(err);
});
};
const showLikeIcon = () => {
const {user: {_id}} = isAuthenticated()
return (
<span>
{/* if user is not signed in, or user = author of post, don't display like icon */}
{post.author && post.author.id === _id || !isAuthenticated() ? (
""
) : (
<img
src={Like}
onClick={() => {
like(id);
}}
alt="Like icon"
/>
)}
</span>
);
};
export default Post;
isAuthenticated()
export const isAuthenticated = () => {
if (typeof window == 'undefined') {
return false;
}
if (localStorage.getItem('jwt')) {
return JSON.parse(localStorage.getItem('jwt'));
} else {
return false;
}
};
形成您的代码,我想当用户登录您的isAuthenticated()
返回数据结构时,例如:
{
...
user: {
_id: id,
...
}
}
这样就可以了{user: {_id}} = isAuthenticated()
。但是,当用户在不签署,它只是回归false
这样isAuthenticated().user
的undefined
,这会导致错误。
要解决此问题,您可以将代码更改为以下内容:
const showLikeIcon = () => {
const {user} = isAuthenticated();
return (
<span>
// if no user then it will not call user._id
{(!user || (post.author && post.author.id === user._id)) ? (
""
) : (
<img
src={Like}
onClick={() => {
like(id);
}}
alt="Like icon"
/>
)}
</span>
);
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句