【问题标题】:Expecting SWR library to return cached data but not happening期望 SWR 库返回缓存数据但没有发生
【发布时间】:2021-06-24 19:36:06
【问题描述】:

我正在使用 Vercel SWR 钩子 usrSWR,我希望我可以在某个遥远的组件中获取存储在缓存中的数据,而不必使用上下文或其他一些全局状态管理器。

具体来说,我在IndexPage 中使用initialData 设置缓存数据,我可以看到返回的data 是正确的,但是当我尝试从OtherComponent 检索相同的数据时,数据返回为未定义。

我在代码框里有代码:https://codesandbox.io/s/useswr-global-cache-example-forked-8qxh7?file=/pages/index.js

import useSWR from "swr";

export default function IndexPage({ speakersData }) {
  const { data } = useSWR("globalState", { initialData: speakersData });

  return (
    <div>
      This is the Index Page <br />
      data: {JSON.stringify(data)}
      <br />
      <OtherComponent></OtherComponent>
    </div>
  );
}

function OtherComponent() {
  const { data } = useSWR("globalState");
  return <div>I'm thinking this should get my global cache but it does not {JSON.stringify(data)}</div>;
}

export async function getServerSideProps() {
  const speakersData = [{ id: 101 }, { id: 102 }];
  return { props: { speakersData: speakersData } };
}

【问题讨论】:

  • 如果您等待几秒钟,您的数据确实会显示出来(“几秒钟”似乎是一个可变的数量,我让它在某个时间点 10 秒后工作,在另一个时间点整整一分钟) ,这...没有帮助)。在OtherComponent 中,可能值得设置refreshIntervalrevalidateOnMount

标签: reactjs react-hooks next.js swr


【解决方案1】:

恐怕您需要将数据向下传递给子组件(或使用 React 上下文)以填充其 initialData,否则它最初不会有任何数据 - 数据传递给 @987654324 @ 不存储在缓存中。

此外,除非您是 provide the fetcher method globally,否则您应该将其传递给 useSWR 调用。

import useSWR from "swr";

const getData = async () => {
  return [{ id: 101 }, { id: 102 }];
};

export default function IndexPage({ speakersData }) {
    const { data } = useSWR("globalState", getData, { initialData: speakersData });

    return (
        <div>
            This is the Index Page <br />
            data: {JSON.stringify(data)}
            <br />
            <OtherComponent speakersData={speakersData}></OtherComponent>
        </div>
    );
}

function OtherComponent({ speakersData }) {
    const { data } = useSWR("globalState", getData, { initialData: speakersData });
    return <div>I'm thinking this should get my global cache but it does not {JSON.stringify(data)}</div>;
}

export async function getServerSideProps() {
    const speakersData = await getData();
    return { props: { speakersData } };
}

【讨论】:

  • 我明白了,因为这就是他们仓库中的示例所做的,但我不明白为什么数据不能作为缓存使用?我认为 useSWR 的目的是使数据在缓存中可用(就像 graphql useQuery 钩子一样)。
  • 传递给initialData 的数据不会存储在缓存中。您必须使用自己的逻辑明确地这样做。这是一个 potential example 扩展了原来的 useSWR 钩子。
猜你喜欢
  • 2023-02-09
  • 2020-12-31
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 2021-08-24
相关资源
最近更新 更多