relay nextjs
v3.0.1
Revere Cre在招聘!有兴趣在前端的最前沿工作吗?
有关更多信息,请与[email protected]联系。
文档|讨论|最新版本
relay-nextjs是同一项目中使用中继和NEXT.js的最佳方法!它支持逐步迁移,已悬念,并由大公司在生产中运行。
relay-nextjs包装页面组件,一个GraphQl查询以及一些使用继电器自动连接数据获取的辅助方法。在初始加载时,创建了继电器环境,数据是服务器端,呈现页面的,并且结果状态被序列化为脚本标签。在客户端的启动时,使用该序列化状态创建了新的继电器环境和预加载查询。使用客户端继电器环境在后续导航中获取数据。
注意: relay-nextjs目前不支持NextJS 13应用程序路由器。
使用NPM或其他喜欢的软件包管理器安装:
$ npm install relay-nextjs relay-nextjs必须在_app中配置以正确拦截和处理路由。
有关继电器环境的基本信息,请参阅“中继文档”。
relay-nextjs的设计考虑了客户端和服务器端渲染。因此,它需要能够使用客户端或服务器端继电器环境。图书馆知道如何处理要使用的环境,但是我们必须告诉它如何创建这些环境。为此,我们将定义两个功能: getClientEnvironment和createServerEnvironment 。请注意区分 - 在客户端上,仅创建了一个环境,因为只有一个应用程序,但是在服务器上,我们必须每播放器创建一个环境,以确保在请求之间不共享缓存。
首先,我们将定义getClientEnvironment :
// lib/client_environment.ts
import { Environment , Network , Store , RecordSource } from 'relay-runtime' ;
export function createClientNetwork ( ) {
return Network . create ( async ( params , variables ) => {
const response = await fetch ( '/api/graphql' , {
method : 'POST' ,
credentials : 'include' ,
headers : {
'Content-Type' : 'application/json' ,
} ,
body : JSON . stringify ( {
query : params . text ,
variables ,
} ) ,
} ) ;
const json = await response . text ( ) ;
return JSON . parse ( json ) ;
} ) ;
}
let clientEnv : Environment | undefined ;
export function getClientEnvironment ( ) {
if ( typeof window === 'undefined' ) return null ;
if ( clientEnv == null ) {
clientEnv = new Environment ( {
network : createClientNetwork ( ) ,
store : new Store ( new RecordSource ( ) ) ,
isServer : false ,
} ) ;
}
return clientEnv ;
}然后createServerEnvironment :
import { graphql } from 'graphql' ;
import { GraphQLResponse , Network } from 'relay-runtime' ;
import { schema } from 'lib/schema' ;
export function createServerNetwork ( ) {
return Network . create ( async ( text , variables ) => {
const context = {
token ,
// More context variables here
} ;
const results = await graphql ( {
schema ,
source : text . text ! ,
variableValues : variables ,
contextValue : context ,
} ) ;
return JSON . parse ( JSON . stringify ( results ) ) as GraphQLResponse ;
} ) ;
}
export function createServerEnvironment ( ) {
return new Environment ( {
network : createServerNetwork ( ) ,
store : new Store ( new RecordSource ( ) ) ,
isServer : true ,
} ) ;
}请注意,在示例服务器环境中,我们正在针对本地模式执行,但您也可以从远程API中获取。
_app // pages/_app.tsx
import { RelayEnvironmentProvider } from 'react-relay/hooks' ;
import { useRelayNextjs } from 'relay-nextjs/app' ;
import { getClientEnvironment } from '../lib/client_environment' ;
function MyApp ( { Component , pageProps } : AppProps ) {
const { env , ... relayProps } = useRelayNextjs ( pageProps , {
createClientEnvironment : ( ) => getClientSideEnvironment ( ) ! ,
} ) ;
return (
< >
< RelayEnvironmentProvider environment = { env } >
< Component { ... pageProps } { ... relayProps } />
</ RelayEnvironmentProvider >
</ >
) ;
}
export default MyApp ; // src/pages/user/[uuid].tsx
import { withRelay , RelayProps } from 'relay-nextjs' ;
import { graphql , usePreloadedQuery } from 'react-relay/hooks' ;
// The $uuid variable is injected automatically from the route.
const ProfileQuery = graphql `
query profile_ProfileQuery($uuid: ID!) {
user(id: $uuid) {
id
firstName
lastName
}
}
` ;
function UserProfile ( { preloadedQuery } : RelayProps < { } , profile_ProfileQuery > ) {
const query = usePreloadedQuery ( ProfileQuery , preloadedQuery ) ;
return (
< div >
Hello { query . user . firstName } { query . user . lastName }
</ div >
) ;
}
function Loading ( ) {
return < div > Loading... </ div > ;
}
export default withRelay ( UserProfile , UserProfileQuery , {
// Fallback to render while the page is loading.
// This property is optional.
fallback : < Loading /> ,
// Create a Relay environment on the client-side.
// Note: This function must always return the same value.
createClientEnvironment : ( ) => getClientEnvironment ( ) ! ,
// variablesFromContext allows you to declare and customize variables for the graphql query.
// by default variablesFromContext is ctx.query
variablesFromContext : ( ctx : NextRouter | NextPageContext ) => ( { ... ctx . query , otherVariable : true } ) ,
// Gets server side props for the page.
serverSideProps : async ( ctx ) => {
// This is an example of getting an auth token from the request context.
// If you don't need to authenticate users this can be removed and return an
// empty object instead.
const { getTokenFromCtx } = await import ( 'lib/server/auth' ) ;
const token = await getTokenFromCtx ( ctx ) ;
if ( token == null ) {
return {
redirect : { destination : '/login' , permanent : false } ,
} ;
}
return { token } ;
} ,
// Server-side props can be accessed as the second argument
// to this function.
createServerEnvironment : async (
ctx ,
// The object returned from serverSideProps. If you don't need a token
// you can remove this argument.
{ token } : { token : string }
) => {
const { createServerEnvironment } = await import ( 'lib/server_environment' ) ;
return createServerEnvironment ( token ) ;
} ,
} ) ;