React 组件不会在状态更改时重新渲染
我的 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,第二次可能是false或true,第三次总是打印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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
后续渲染将忽略初始状态。您必须使用
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.