React 上下文 - Post 喜欢/不喜欢的功能

React Context - Post Like / Unlike feature

我正在 uilding post 喜欢/不喜欢使用 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, res) => {
  try {
    const result = await Post.findByIdAndUpdate(
      req.body.postId,
      {
        $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`,
        { userId, postId },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );
      dispatch({ type: "UNLIKE_POST", payload: res.data });
    } catch (err) {
      console.log(err);
    }
  };

减速器

case "LIKE_POST":
      return {
        ...state,
        posts: // ???
        ),
      };
case "UNLIKE_POST":
      return {
        ...state,
        posts: // ???,
      };

reducer 的逻辑应该是什么?

像这样:

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