如何确保只有对象的所有者才能看到按钮(ReactJS/NodeJS)



如何为前端编写考虑可见性逻辑的代码,只有对象的所有者才能看到按钮?

在我的后端,如果comments表中的user_id与req对象中的user.id匹配,那么用户将能够删除注释。我已经通过Postman测试过了,它在后端运行正常。

我不知道如何在前端编写代码。前端的第4行(下图(不正确,但我想象的是这样的。

前端:

function DtcCommentDeleteButton({ comment }) {
return (
<span className="FilteredDtcCommentListItem__button">
{comment.user_id !== req.user.id ? (
null
): (
<button
onClick={(e) => this.handleDelete(e)}
className="FilteredDtcCommentListItem__delete">
Delete
</button>
)}
</span>
)

后端:

.delete(requireAuth, async (req, res, next) => {
const knexInstance = req.app.get("db");
const comment = await CommentsService.getById(knexInstance, req.params.id);
if (comment === undefined) {
return res.status(404).json({
error: {
message: `Comment doesn't exist.`,
},
});
}
if (comment.user_id !== req.user.id) {
return res.status(401).json({
error: {
message: `You can only delete your own comments!`,
},
});
}
CommentsService.deleteComment(knexInstance, req.params.id)
.then((numRowsAffected) => {
res.status(204).end();
})
.catch(next);
})

我目前正在调查的资源:

(1( ReactJS确保只有对象的所有者才能编辑/删除

这是我的解决方案。在前端组件中,我添加了以下代码块。在context.js中,我添加了以下代码块和其他几行代码:

组件:

function DtcCommentDeleteButton({ comment, userId, deleteComment, setError }) {
return (
<span className="FilteredDtcCommentListItem__span">
{comment.user_id.id !== parseInt(userId) ? null : (
<button
className="FilteredDtcCommentListItem__button"
onClick={() =>
handleDeleteComment(comment.id, userId, deleteComment, setError)
}
>
Delete
</button>
)}
</span>
);
}

上下文:

setUser = (payload) => {
this.setState({ user_id: payload.user_id });
localStorage.user_id = payload.user_id;
};

它现在正在工作。:(

最新更新