React 组件不会在状态更改时重新渲染

发布于 2025-01-14 05:36:43 字数 1552 浏览 1 评论 0原文

我的 Profile.js 功能组件中有这个状态

  const [isFollowing, setIsFollowing] = useState(
    user?.followings.includes(proUser?._id)
  );

基于状态的条件渲染

return (
...
 <button onClick={followUser}>
   {isFollowing ? "Unfollow" : "Follow"}
  </button>
...

我 100% 确定 < strong>user?.followings.includes(proUser?._id) 是 true 但按钮仍然显示“follow”,所以我控制台记录它以查看发生了什么:

 console.log(user?.followings.includes(proUser?._id);

该组件将重新-渲染3第一次打印false,第二次可能是falsetrue,第三次总是打印true,但状态仍然为 false,组件不会在状态更改时重新渲染,甚至状态也不会更改,为什么会发生这种情况以及如何修复它?

followUser 函数,如果您想看一下:

  const followUser = async () => {
    if (isFollowing) {
      await fetch(`http://localhost:8000/unfollow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "UNFOLLOW", payload: id });
    } else {
      await fetch(`http://localhost:8000/follow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "FOLLOW", payload: id });
    }

    setIsFollowing(!isFollowing);
  };

i have this state in my Profile.js functional component:

  const [isFollowing, setIsFollowing] = useState(
    user?.followings.includes(proUser?._id)
  );

conditional rendering based on state:

return (
...
 <button onClick={followUser}>
   {isFollowing ? "Unfollow" : "Follow"}
  </button>
...

I'm 100% sure that the result of user?.followings.includes(proUser?._id) is true but the button still says "follow", so i console log it to see what's happening :

 console.log(user?.followings.includes(proUser?._id);

the component will re-render 3 times, first time it prints false, second time may be either false or true, the third time it always print true, but the state is still false, the component will not re-render on state change and even the state won't change, why is that happening and how to fix it?

followUser function in case you want to take a look:

  const followUser = async () => {
    if (isFollowing) {
      await fetch(`http://localhost:8000/unfollow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "UNFOLLOW", payload: id });
    } else {
      await fetch(`http://localhost:8000/follow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "FOLLOW", payload: id });
    }

    setIsFollowing(!isFollowing);
  };

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍白女子 2025-01-21 05:36:43

后续渲染将忽略初始状态。您必须使用 setIsFollowing(user?.followings.includes(proUser?._id)) 来代替。

将其放入 useEffect 中即可运行。

Initial state will be disregarded for subsequent renders. You must use setIsFollowing(user?.followings.includes(proUser?._id)) instead.

Put it into useEffect and it will work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文