我正在使用Vercel SWR钩子usrSWR,我希望我可以在某个遥远的组件中获得存储在缓存中的数据,而不必使用上下文或其他全局状态管理器。
具体来说,我用initialData设置IndexPage
中的缓存数据,我可以看到返回的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 } };
}
恐怕您还需要将数据传递给子组件(或使用React Context(来填充其initialData
,否则它最初不会有任何数据-传递给initialData
的数据不会存储在缓存中。
此外,除非全局提供fetcher
方法,否则应将其传递给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 } };
}