反应-用户界面未正确更新

时间:2020-08-29 16:45:22

标签: reactjs react-context

我正在尝试使用React Context构建用户关注和关注者功能。如果登录用户正在查看自己的个人资料,那么他可以看到“编辑/删除”按钮。当他单击其他个人资料时,关注/取消关注按钮。问题是,当我单击“跟随”按钮时,“跟随”按钮被“编辑”和“删除”按钮代替,而不是“取消关注”按钮,但是,如果此时刷新页面,它会正确显示“取消关注”。

上下文文件:

const initialState = {
  loggedInUser: null,
};

// Add following / follower
  const follow = async (userId, followId) => {
    try {
      const res = await axios.put(
        "/api/users/follow",
        { userId, followId },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );
      dispatch({ type: "FOLLOW", payload: res.data });
    } catch (err) {
      console.log(err);
    }
  };

  // Remove following / follower
  const unfollow = async (userId, unfollowId) => {
    try {
      const res = await axios.put(
        "/api/users/unfollow",
        { userId, unfollowId },
        {
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        }
      );      
      dispatch({ type: "UNFOLLOW", payload: res.data });
    } catch (err) {
      console.log(err);
    }
  };

减速器:

 case "FOLLOW":
      return {
        ...state,
        loggedInUser: action.payload,
      };
    case "UNFOLLOW":
      return {
        ...state,
        loggedInUser: action.payload,

个人资料

// user = profile currently being viewed and it is working fine
{loggedInUser && loggedInUser._id === user._id ? (
                <>
                  <Link to={`/user/edit/${user._id}`} className={classes.link}>
                    <IconButton color="primary">
                      <Edit />
                    </IconButton>
                  </Link>

                  <IconButton onClick={() => handleDelete()}>
                    <Delete color="error" />
                  </IconButton>
                </>
              ) : loggedInUser.following.includes(user._id) ? (
                <Button onClick={() => unfollow(loggedInUser._id, user._id)}>
                  UNFOLLOW
                </Button>
              ) : (
                <Button onClick={() => follow(loggedInUser._id, user._id)}>
                  FOLLOW
                </Button>
              )}

我在做什么错了?

编辑 替换

loggedInUser.following.includes(user._id) ? (
                <Button onClick={() => unfollow(loggedInUser._id, user._id)}>

使用

user.followers.some(follower => follower._id === loggedInUser._id) ? (
                <Button onClick={() => unfollow(loggedInUser._id, user._id)}>
                  UNFOLLOW
                </Button>

现在,当我单击“关注/取消关注”时,没有显示“编辑”和“删除”按钮,但是仍然需要刷新页面才能看到更新的UI。

0 个答案:

没有答案