简体   繁体   English

为什么我没有取回 useState 的新值 - React.JS?

[英]Why I'm not getting back the new value of useState - React.JS?

In the line setVotedPosts([...previousVotedPosts, postId]);在行 setVotedPosts([...previousVotedPosts, postId]);

I'm trying to get the previous value of votedPosts, but I'm getting back the newest value.我试图获得votedPosts 的先前值,但我正在取回最新值。

full code : https://github.com/silvertechguy/reddit-clone/blob/main/src/components/vote-buttons.js完整代码: https : //github.com/silvertechguy/reddit-clone/blob/main/src/components/vote-buttons.js

App live : https://reddit-clone-official.vercel.app/应用直播: 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);

Problem问题

const previousVotedPosts = votedPosts;

In JavaScript, arrays are reference types, so you can't just create a new copy of an array using = .在 JavaScript 中,数组是引用类型,因此您不能仅使用=创建数组的新副本。

Try this solution试试这个解决方案

Clone array using spread syntax( ... ).使用扩展语法( ... )克隆数组。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM