跳至主要内容

中继环境

要使用 recoil-relay 库与 GraphQL 协同工作,您需要引用您的 Relay 环境。每个 GraphQL 选择器效应 都需要一个 environment 选项,该选项可以引用 Relay 环境,也可以是 EnvironmentKey,该键与 <RecoilRelayEnvironment> 组件匹配,该组件注册了 Relay 环境。

EnvironmentKey

当在 GraphQL 查询中使用 EnvironmentKey 时,它会与您 <RecoilRoot> 中的具有相同 environmentKey 的周围 <RecoilRelayEnvironment> 匹配。当环境对象仅在运行时(实际渲染组件时)可用时,这很有用,例如用于 预加载查询

const myEnvironmentKey = new EnvironmentKey('My Environment');

function MyApp() {
const myEnvironment = useMyRelayEnvironment();
return (
<RecoilRoot>
<RecoilRelayEnvironment
environment={myEnvironment}
environmentKey={myEnvironmentKey}>
{/* Components here can use Recoil atoms/selectors which reference myEnvironmentKey */}
</RecoilRelayEnvironment>
</RecoilRoot>
)
}

环境提供者

要使用 Relay 钩子(例如用于提交突变)与您的环境协同工作,<RelayEnvironmentProvider> 组件仍然是必需的。为了方便起见,有一个 <RecoilRelayEnvironmentProvider> 组件,它结合了 <RecoilRelayEnvironment><RelayEnvironmentProvider>

const myEnvironmentKey = new EnvironmentKey('My Environment');

function MyApp() {
return (
<RecoilRoot>
<RecoilRelayEnvironmentProvider
environment={myEnvironment}
environmentKey={myEnvironmentKey}>
{/* Components here can use both Recoil and Relay APIs for GraphQL */}
</RecoilRelayEnvironmentProvider>
</RecoilRoot>
)
}