期望 SWR 库返回缓存数据但没有发生

时间:2021-03-28 15:13:35

标签: reactjs react-hooks next.js swr

我正在使用 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 } };
}

1 个答案:

答案 0 :(得分:0)

恐怕您还需要将数据向下传递给子组件(或使用 React Context)来填充它的 initialData,否则它最初不会有任何数据 - 数据传递给initialData 未存储在缓存中。

此外,除非您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 } };
}