Typescript 如果您有apollo react钩子从后端获取数据,那么如何使用nextjs进行服务器端渲染?
我有一个nextjs项目,它使用apollo graphql从后端获取数据。我正在尝试使用服务器端呈现来呈现我的页面。但我目前正在使用graphql apollo react钩子从后端获取数据,react钩子阻止我在getServerSideProps内部调用后端 我如何解决这个问题Typescript 如果您有apollo react钩子从后端获取数据,那么如何使用nextjs进行服务器端渲染?,typescript,graphql,react-hooks,next.js,server-side-rendering,Typescript,Graphql,React Hooks,Next.js,Server Side Rendering,我有一个nextjs项目,它使用apollo graphql从后端获取数据。我正在尝试使用服务器端呈现来呈现我的页面。但我目前正在使用graphql apollo react钩子从后端获取数据,react钩子阻止我在getServerSideProps内部调用后端 我如何解决这个问题 import * as React from "react"; import { useExampleQuery } from "graphql/types"; expor
import * as React from "react";
import { useExampleQuery } from "graphql/types";
export const getServerSideProps = async ({ params }) => {
// Here we should probably call graphql function that is now called inside Page
return { props: { hash: params.hash } };
};
const Page = ({ hash }) => {
/*
I am currently calling my graphql query here using apollo react hooks,
that are generated inside graphql/types using @graphql-codegen (typescript)
*/
const { data, loading } = useExampleQuery({
variables: {
hash: hash,
},
});
return loading ? <p>{loading}</p> : <p>{data.example.text}</p>;
};
export default Page;
import*as React from“React”;
从“graphql/types”导入{useExampleQuery};
export const getServerSideProps=async({params})=>{
//在这里,我们可能应该调用现在在页面内部调用的graphql函数
返回{props:{hash:params.hash};
};
常量页=({hash})=>{
/*
我目前正在使用apollo react钩子调用我的graphql查询,
使用@graphqlcodegen(typescript)在graphql/types内部生成的
*/
const{data,loading}=useExampleQuery({
变量:{
散列:散列,
},
});
返回加载?{loading}:{data.example.text};
};
导出默认页面;
getServerSideProps
是一个服务器端函数,因此您不能完全调用其中的apollo查询挂钩
一种方法是使用apollo客户端实例查询方法
请参见下面的示例代码
从'@apollo/client'导入{gql};
从“/path/to/graphql/server/client”导入客户端;
//示例查询
常量示例_QUERY=gql`
查询示例\u查询($hash:String!){
示例查询(哈希:$hash){
...
}
}
`;
export const getServerSideProps=async({params})=>{
const{data}=await apolloClient.query({
查询:示例查询,
变量:{hash:params.hash},
});
返回{
道具:{
hash:params.hash,
数据,
},
};
};
另外,如果导入apollo客户机服务器实例有点不清楚,可以使用此包在给定URL的情况下发出graphql请求
参见示例
从“graphql请求”导入{GraphQLClient};
//将下面的图形URL替换为实际
const client=new GraphQLClient();
export const getServerSideProps=async({params})=>{
const{data}=await client.request(示例_QUERY{
hash:params.hash
});
返回{
道具:{
hash:params.hash,
数据,
},
};
};
谢谢,真的很有帮助!所以,正如您所说,我正在尝试创建一个新的graphql客户机,但我得到了一个“网络错误:请求失败,原因:connect-econnrefered127.0.0.1:3001”。你知道问题出在哪里吗?我可以访问其他URL。当apollo客户端在我的initApollo文件中初始化时,我没有收到该错误,但我无法从initApollo内部访问该客户端。请导出在您的initApollo
文件中工作的客户端并在此处使用该实例。但是,我可以看看您是如何创建一个新的graphql客户端的吗@无调性