[英]How to use SSR data fetching in nextjs with apollo client?
I am try to use apollo-client
with nextjs.我正在尝试将
apollo-client
与 nextjs 一起使用。 Here I want to fetch data in getServerSideProps
.在这里我想在
getServerSideProps
中获取数据。 Suppose I have 2 components and one page-假设我有 2 个组件和一页 -
section.tsx
this is component-1 section.tsx
这是组件 1
const Section = () => {
return (
<div>
Section
</div>
);
};
export default Section;
mobile.tsx
this is component 2 mobile.tsx
这是组件 2
const Mobile = () => {
return (
<div>
Mobile
</div>
);
};
export default Mobile;
Now I call this two component into home page.现在我将这两个组件调用到主页中。
index.tsx
- index.tsx
-
const Home: NextPage = () => {
return (
<Container disableGutters maxWidth="xxl">
<Section />
<Mobile />
</Container>
);
};
export default Home;
export const getServerSideProps: GetServerSideProps = async () => {
const { data } = await client.query({ query: GET_USER_LIST })
return { props: {} }
}
Here you can see that in getServerSideProps
I already fetch my data.在这里你可以看到在
getServerSideProps
中我已经获取了我的数据。
My question is How can I directly access this data form Section
component and Mobile
component without passing props.我的问题是如何在不传递道具的情况下直接访问此数据表单
Section
组件和Mobile
组件。 I don't want to pass props, because if my component tree will be more longer, then it will be difficult to manage props.我不想传递 props,因为如果我的组件树会更长,那么 props 将很难管理。
From appollo
docs, I alreay know that apollo client
do the same with redux
state manager.从
appollo
文档,我已经知道apollo client
对redux
state 经理做同样的事情。 So please tell me how can I access this data from any component that already fetched in getServerSideProps
.所以请告诉我如何从已经在
getServerSideProps
中获取的任何组件访问这些数据。 Is it possible?.可能吗?。 If not then how can what is the solutions.
如果不是那么怎么解决呢。
How about using context
api if you want to avoid prop drilling?如果你想避免道具钻探,使用
context
api 怎么样? By putting data into context, you can access it from any child component.通过将数据放入上下文中,您可以从任何子组件访问它。 Get the data from the SSR and put it into the context.
从 SSR 中获取数据并将其放入上下文中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.