如果用户喜欢某个帖子,我试图使其显示出充满的心,而如果用户不喜欢它,则可以不显示。我不确定如何执行此操作。
如果我可以使后端工作,则可以基于后端的数据从后端检索数据,并将setState设置为true或false。
我正在使用bookshelf orm
这是即时消息发出类似请求的方式。
router.post('/like/:id', (req, res) => {
const { id } = req.params;
if(id !== null || 'undefined'){
Image.forge({id})
.fetch({ withRelated: ["user", "comments", "likes"] })
.then(likes => {
const like = likes.toJSON();
// console.log(like.likes);
const existingUserlikes = like.likes.map( (user) => user.user_id);
// checking to see if a user already liked his own post
// if existing user does not have user id, user can like post,
// else if user already like this post wont be able to.
const newLike = new Likes({
image_id: id,
user_id: req.user.id,
likedByme: req.user.id === likes.likes.user_id ? false : true
});
if(existingUserlikes.includes(req.user.id)){
// !newLike do not create a new row of likes if like from this user already exists
if(!newLike){
Likes.forge().where({ user_id: req.user.id, image_id: id}).destroy();
}
return res.status(500).json({status: "You already liked this post", like: newLike})
}
else{
newLike.save().then(like => {
return res.status(200).json({ status:"You liked this post", like: newLike})
})
}
});
}
})
我如何检查用户是否喜欢帖子,如果他们喜欢将帖子设置为true(如果不是false)。通过他们,我可以使用这些信息来填充心脏或使心脏不填充。
这是即时获取数据的方式。
router.get("/uploads", (req, res) => {
Image.query(image => {
image.orderBy("img_url", "DESC");
image.limit(10);
// if you want to include the user with the image, you would use the withRelated
// comments.user gets the user within the comments array
})
.fetchAll({
withRelated: [
"user",
{
comments: qb => {
qb.orderBy("created_at", "ASC");
}
},
"comments.user",
"likes"
]
})
.then(images => {
return res.status(200).json(images.toJSON());
});
});
顶表
export const up = async knex => {
await knex.schema.createTable("likes", t => {
t.increments("id").primary().unsigned();
t.integer("user_id").unsigned().references("id").inTable("users");
t.integer("image_id").unsigned().references("id").inTable("images");
t.string('likedByme').defaultTo(false);
t.timestamp("created_at").defaultTo(knex.fn.now());
t.timestamp("deleted_at").defaultTo(knex.fn.now());
t.timestamp('restored_at').defaultTo(knex.fn.now());
t.timestamp("updated_at").defaultTo(knex.fn.now());
});
};
export const down = async knex => {
await knex.schema.dropTable("likes");
};