0

我有一个组件可以获取带有帖子的 subreddit 的数据,并且每个帖子都有投票:

const subUrl = `/api/subreddit/findSubreddit?name=${sub}`;

  const { data: fullSub, error } = useSWR(subUrl, fetchData, {
    initialData: props.fullSub, //comes from next.js getServerSideProps
  });

这工作得很好,它可以在屏幕上呈现所有内容。但是在我的subredditPost组件上(我为每个帖子渲染一个subredditPost),当我单击 upvote 按钮时,我有这个 onClick 函数:

const upvotePost = async (postid, fullSub, subUrl) => {
  console.log("the sub variable is: ", subUrl); //same url as in the main component
  mutate(
    subUrl,
    async (data) => {
    // this is undefined when I hit on the upvote button
    // Expected: The current state of swr with the key of subUrl
      console.log("cached value: ", data);
      return {
        ...data,
        posts: data.posts.map((post) => {
          if (post.id === postid) {
            return {
              ...post,
              votes: [...post.votes, { voteType: "UPVOTE" }],
            };
          } else {
            return post;
          }
        }),
      };
    },
    false
  );
  const res = await fetch("/api/post/upvote", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ postId: postid }),
  });
  mutate(subUrl);
};

它始终在上面代码的 console.log 中未定义。所以我收到一个错误,页面上不再呈现任何内容。我究竟做错了什么?如果我使用不同的密钥,我读到它无法获取缓存,但我使用的是相同的密钥。我将subUrl我的主要组件(我在其中获取 subreddit)传递给 post 组件(我在其中单击 upvote 按钮)。所以它是完全一样的。

为什么我会不确定?

4

1 回答 1

1

我能够通过提供如下默认值来解决此问题mutate

mutate(
    sub,
    async (data = fullSub) => {
      console.log("cached value: ", data);
      return {
        ...data,
        posts: data.posts.map((post) => {
          if (post.id === postid) {
            return {
              ...post,
              votes: [...post.votes, { voteType: "UPVOTE" }],
            };
          } else {
            return post;
          }
        }),
      };
    },
    false
  );

因此,如果未定义异步函数,请给它一个默认值:async (data = fullSub)

这解决了它,但仍然不清楚为什么它是未定义的?也许有人可以回答这个问题。我将暂时保持开放状态,一段时间后如果没有人有更好的答案,我会标记我的。

于 2021-01-07T13:19:49.610 回答