【发布时间】: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中,可能值得设置refreshInterval或revalidateOnMount?
标签: reactjs react-hooks next.js swr