反应原生 - 像图标动作一样反应上下文 [英] react native - react context like icon action
问题描述
我目前使用 react 上下文存储我的用户,每个用户可以喜欢任意数量的帖子.
I am currently storing my user using react context, each user can like as many posts as they want.
我的后端有一个名为 isLiked 的参数,对于每个用户的每个帖子,它可以是 true 或 false.
i have a parameter called isLiked in my backend that can either be true or false for each post for each user.
这是我的代码:
我尝试了一个解决方案,我的问题是当我按下轮廓的心来喜欢一个帖子时,它会变成一个心,这样的记录在我的数据库中排序,但是当我关闭帖子并再次打开它时不改变,我需要刷新应用才能改变.
I attempted a solution, my problem is that when i press the outlined heart to like a post it changes to a heart and a record of this like is sorted in my database but when i close the post and open it again it does not change, i need to refresh app in order for it to change.
尝试过的解决方案
Postdetailsscreen.js
Postdetailsscreen.js
const post=route.params;
const [addedToLikes, setAddedToLikes] = useState(post.isLiked);
const addToLikes = (PostId,userId) => {
setAddedToLikes(!addedToLikes);
likePost({PostId,userId});
};
<TouchableOpacity
onPress={() => {
addToLikes(post.id,user.id);
}}
>
{addedToLikes ?
<MaterialCommunityIcons
name="heart"
/>
:
<MaterialCommunityIcons
name="heart-outline"
/>}
</TouchableOpacity>
在我的后端,我有一个 isLiked 参数,如果在我的喜欢表中找到当前的 userId 和 postId,则 isLiked 为真,否则为假.
in my backend i have an isLiked parameter that if the current userId and postId are found in my likes table then isLiked is true otherwise false.
这是我的后端代码:-
router.get("/",
auth,
async (req, res) => {
const posts = await Post.findAll({
order: [["createdAt", "DESC"]],
include: [
{ model: User, attributes: ["id", "name", "email"] },
{ model: Post_Image, attributes: ["id", "images"] },
]})
if (!posts) return res.status(404).send();
const baseUrl = config.get("assetsBaseUrl");
const plainPosts = posts.map((x) => x.get({ plain: true }));
const resultPosts = [];
for (const post of plainPosts) {
const isLiked = post.Likes.some(x => x.userId === req.user.id);
const { Post_Images, ...postAttributes } = listing;
const IMAGES = Post_Images.map((postImage) => ({
url: `${baseUrl}${postImage.images}_full.jpg`,
thumbnailUrl: `${baseUrl}${postImage.images}_thumb.jpg`,
}));
resultPosts.push({ ...postAttributes, images: IMAGES
,isLiked
});
}
res.send(resultPosts);
});
如果用户喜欢帖子,即使不刷新应用程序,图标也会保持填充状态,有人可以帮助我吗?
Can someone help me with that if a user liked a post the icon stays filled even without refreshing the app?
推荐答案
假设你从父组件获取 props.
Assuming you are getting the props from parent component.
const Heart = ({ isLiked }) => {
const [ liked, setLiked ] = useState(false);
useEffect(() => {
setLiked(isLiked)
},[isLiked])
......
}
使用 useEffect 确保在 isLiked 属性更改时更新您的状态.
use useEffect to make sure you update your state whenever the isLiked prop changes.
然后在你的父母组件中.
Then in your parents component.
const ListofPost = () => {
const data = fetchTheData(url);
....
return ( data.map( item => <Heart isLiked={item.isLiked} />) )
}
这篇关于反应原生 - 像图标动作一样反应上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!