React 组件不会在状态更改时重新渲染
React component doesn't re-render on state change
我的Profile.js功能组件中有这个状态:
const [isFollowing, setIsFollowing] = useState(
user?.followings.includes(proUser?._id)
);
条件渲染 基于状态:
return (
...
<button onClick={followUser}>
{isFollowing ? "Unfollow" : "Follow"}
</button>
...
我 100% 确定 user?.followings.includes(proUser?._id) 的结果是 true 但按钮仍然显示“关注”,所以我控制台记录它以查看发生了什么:
console.log(user?.followings.includes(proUser?._id);
该组件将重新渲染 3 次,第一次它打印 false,第二次可能是 false 或 true,第三次总是打印true,但状态仍然是false,组件不会在状态改变时重新渲染,甚至状态不会'没有改变,为什么会发生这种情况以及如何解决?
关注用户功能如果你想看一看:
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);
};
后续渲染将忽略初始状态。您必须改用 setIsFollowing(user?.followings.includes(proUser?._id))
。
放入useEffect
即可。
我的Profile.js功能组件中有这个状态:
const [isFollowing, setIsFollowing] = useState(
user?.followings.includes(proUser?._id)
);
条件渲染 基于状态:
return (
...
<button onClick={followUser}>
{isFollowing ? "Unfollow" : "Follow"}
</button>
...
我 100% 确定 user?.followings.includes(proUser?._id) 的结果是 true 但按钮仍然显示“关注”,所以我控制台记录它以查看发生了什么:
console.log(user?.followings.includes(proUser?._id);
该组件将重新渲染 3 次,第一次它打印 false,第二次可能是 false 或 true,第三次总是打印true,但状态仍然是false,组件不会在状态改变时重新渲染,甚至状态不会'没有改变,为什么会发生这种情况以及如何解决?
关注用户功能如果你想看一看:
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);
};
后续渲染将忽略初始状态。您必须改用 setIsFollowing(user?.followings.includes(proUser?._id))
。
放入useEffect
即可。