为什么我不找回useState的新价值-React.JS?

时间:2020-10-31 09:20:08

标签: javascript reactjs

在setVotedPosts([... previousVotedPosts,postId])行中;

我正在尝试获取前已投票的值,但我正在获取最新的值。

完整代码: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);

1 个答案:

答案 0 :(得分:0)

问题

const previousVotedPosts = votedPosts;

在JavaScript中,数组是引用类型,因此不能仅使用=创建数组的新副本。

尝试此解决方案

使用扩展语法(...)克隆数组。

  const handleDisablingOfVoting = (postId) => {
    const previousVotedPosts = [...votedPosts];
    setVotedPosts([...previousVotedPosts, postId]);

    localStorage.setItem(
      "votes",
      JSON.stringify([...previousVotedPosts, postId])
    );
  };