【发布时间】:2021-02-13 14:42:16
【问题描述】:
在 setVotedPosts([...previousVotedPosts, postId]); 行中
我正在尝试获取以前的 votedPosts 值,但我正在取回最新的值。
完整代码:https://github.com/silvertechguy/reddit-clone/blob/main/src/components/vote-buttons.js
应用直播:https://reddit-clone-official.vercel.app/
const VoteButtons = ({ post }) => {
const [isVoting, setVoting] = useState(false);
const [votedPosts, setVotedPosts] = useState([]);
useEffect(() => {
const votesFromLocalStorage =
JSON.parse(localStorage.getItem("votes")) || [];
setVotedPosts(votesFromLocalStorage);
}, []);
const handleDisablingOfVoting = (postId) => {
const previousVotedPosts = votedPosts;
setVotedPosts([...previousVotedPosts, postId]);
localStorage.setItem(
"votes",
JSON.stringify([...previousVotedPosts, postId])
);
};
const handleClick = async (type) => {
setVoting(true);
// Do calculation to save the vote.
let upVotesCount = post.upVotesCount;
let downVotesCount = post.downVotesCount;
const date = new Date();
if (type === "upvote") {
upVotesCount = upVotesCount + 1;
} else {
downVotesCount = downVotesCount + 1;
}
await db.collection("posts").doc(post.id).set({
title: post.title,
upVotesCount,
downVotesCount,
createdAt: post.createdAt,
updatedAt: date.toUTCString(),
});
// Disable the voting button once the voting is successful.
handleDisablingOfVoting(post.id);
setVoting(false);
};
const checkIfPostIsAlreadyVoted = () => votedPosts.includes(post.id);
【问题讨论】:
-
previousVotedPosts- 这将在您调用setVotedPosts函数更新状态之前引用状态值。您尝试访问votedPosts的哪个先前值? -
在我更新状态 (setVotedPosts) 并尝试获取更新后的状态后,我总是返回一个空数组。
-
状态是异步更新的,组件只有在重新渲染后才能看到更新后的状态。如果要记录更新的状态,请使用
useEffect钩子。 -
有什么办法可以防止 useEffect 钩子在第一次运行?
-
我想在每次 votedPosts 更改时运行 useEffect,方法是将它添加到 useEffect 的依赖数组中。但我不想第一次运行它。
标签: javascript reactjs