我试图防止用户在刷新页面时多次喜欢照片。
所以当前的不正确的流是:点击所需照片上的“喜欢”〉数字增量〉刷新页面〉click like on desired photo > number increments > refresh the page > *rinse & repeat*
正确的流程应为:click like on desired photo > number increments > refresh the page > click like on desired photo > number decrements > *rinse & repeat*
我知道我需要将喜欢的UserID
Map到本地存储中,这样浏览器就可以记住哪些照片是喜欢的,但我不知道怎么做。
下面是我在else{}
块中的许多尝试之一。我完全碰壁了,不知道如何实现这一点。
**注意:**使用本地存储对我来说并不新鲜,正如你所看到的,我在return()
中使用它是为了一些不相关的事情。
useEffect(() => {
const headers = {
"Accept": 'application/json',
"Authorization": `Bearer ${authToken}`
};
axios.get('http://127.0.0.1:8000/api/get-user-uploads-data', {headers})
.then(resp => {
console.log(resp.data);
setGridData(resp.data);
}).catch(err => {
console.log(err);
});
}, []);
const handleLikesBasedOnUserId = (likedPhotoUserId, userName) => {
let mapOfLikes = {};
if(userLikedPhotos[likedPhotoUserId]) {
// dislike
delete userLikedPhotos[likedPhotoUserId];
gridData.find(photo => photo.UserID === likedPhotoUserId).likes--;
handleDislike(likedPhotoUserId, userName); // Send dislike incrementation via POST request
// localstorage logic?
} else {
// like
userLikedPhotos[likedPhotoUserId] = true;
gridData.find(photo => photo.UserID === likedPhotoUserId).likes++;
// attempt below
mapOfLikes[likedPhotoUserId] = mapOfLikes[likedPhotoUserId] ?? 1;
localStorage.setItem('mapOfLikes', JSON.stringify(mapOfLikes));
handleLike(likedPhotoUserId, userName); // Send like incrementation via POST request
// localstorage logic?
}
// Spread the userLikedPhotos to create a new object and force a rendering
setUserLikedPhotos({...userLikedPhotos});
};
return(
{
gridData.map((photos, index) => {
<span className="likesAmt">❤️ {photos.likes}</span><br/><Button variant="success" onClick={() => handleLikesBasedOnUserId(photos.UserID, photos.name)}>Like</Button><br/><span className="name">{photos.name} {localStorage.getItem('UserID') === photos.UserID ? <h6 className="you">(You)</h6> : null}</span>
})
}
);
2条答案
按热度按时间n6lpvg4x1#
并Map数组列表UserLikedImageList
uplii1fm2#