问题描述
我正在使用React上下文构建类似/与众不同的功能,但是我不知道在reducer中要如何更新UI。目前,当我单击“喜欢/不喜欢”按钮时,ui不会立即更新,必须刷新页面才能查看更新。
后端逻辑
exports.likePost = async (req,res) => {
try {
const result = await Post.findByIdAndUpdate(
req.body.postId,{
$push: { likes: req.body.userId },},{ new: true }
);
return res.json(result);
} catch (err) {
console.log(err.message);
}
};
exports.unlikePost = async (req,{
$pull: { likes: req.body.userId },{ new: true }
);
return res.json(result);
} catch (err) {
console.log(err.message);
}
};
组件
{post.likes.includes(loggedInUser._id) ? (
<IconButton
color="secondary"
component="span"
onClick={() => unlikePost(loggedInUser._id,post._id)}
>
<Like />
</IconButton>
) : (
<IconButton
color="secondary"
component="span"
onClick={() => likePost(loggedInUser._id,post._id)}
>
<Unlike />
</IconButton>
)}
上下文
const initialState = {
posts: [],};
// Like post
const likePost = async (userId,postId) => {
try {
const res = await axios.put(
`/api/posts/like`,{ userId,postId },{
headers: {
"Content-Type": "application/json",Authorization: `Bearer ${localStorage.getItem("token")}`,}
);
dispatch({ type: "LIKE_POST",payload: res.data });
} catch (err) {
console.log(err);
}
};
// Unlike post
const unlikePost = async (userId,postId) => {
try {
const res = await axios.put(
`/api/posts/unlike`,}
);
dispatch({ type: "UNLIKE_POST",payload: res.data });
} catch (err) {
console.log(err);
}
};
减速器
case "LIKE_POST":
return {
...state,posts: // ???
),};
case "UNLIKE_POST":
return {
...state,posts: // ???,};
减速器的逻辑应该是什么?
解决方法
类似这样的东西:
case "LIKE_POST":
return {
...state,like: action.likeValue,};
case "UNLIKE_POST":
return {
...state,unlike: action.unlikeValue,};
要更改值时:
dispatch({ type: "LIKE_POST",likeValue: res.data });
dispatch({ type: "UNLIKE_POST",unlikeValue: res.data });
在您的初始状态:
const initialState = {
posts: [],like: [],unlike: [],};
这是一个很好的解释,对我有帮助:link