【发布时间】:2018-09-02 13:09:32
【问题描述】:
我们目前正在从 Relay 转移到 React Apollo 2.1,而我正在做的事情似乎很可疑。
上下文:某些组件必须仅在用户通过身份验证(通过 API 密钥)时才能呈现,因此有一个 Authenticator 组件保护树的其余部分。
在App.js 中,它是这样使用的(显然,下面所有的 sn-ps 都是最小的示例):
import React from 'react';
import Authenticator from './Authenticator';
import MyComponent from './MyComponent';
export default function App({ apiKey }) {
return (
<Authenticator apiKey={apiKey}
render={({ error, token }) => {
if (error) return <div>{error.message}</div>;
if (token) return <MyComponent token={token} />;
return <div>Authenticating...</div>;
}}
/>
);
}
如果认证成功,MyComponent 会被渲染。
Authentication 在第一次渲染/安装时将身份验证突变发送到服务器,并相应地调用 render prop。
Authentication.js 看起来像这样:
import gql from 'graphql-tag';
import React from 'react';
import { Mutation } from 'react-apollo';
const AUTH_MUTATION = gql`mutation Login($apiKey: String!) {
login(apiKey: $apiKey) {
token
}
}`;
export default function Authenticator({ apiKey, render }) {
return (
<Mutation mutation={AUTH_MUTATION} variables={{ apiKey }}>
{(login, { data, error, called }) => {
if (!called) login(); // ⚠️ This seems sketchy ⚠️
const token = (data && data.login.token) || undefined;
return render({ error, token });
}}
</Mutation>
);
}
if (!called) login(); 让我停下来。如果我不指定if (!called),UI 会变得癫痫并发送数千个请求(这是有道理的,调用login() 会导致render() 重新运行),但它应该如何使用?
似乎Query component equivalent 的不同之处在于它只是简单地渲染它会发出请求。我想知道是否有办法将相同的机制应用于Mutation,这需要调用 mutate 函数作为渲染属性的一部分。
上面 sn-p 的 Relay 等效项与 React Apollo 的 Query 对 Mutation 所做的完全相同:
// Authentication.js
import React from 'react';
import { graphql, QueryRenderer } from 'react-relay';
import { Environment } from 'relay-runtime';
// Hiding out all the `Environment`-related boilerplate
const environment = return new Environment(/* ... */);
const AUTH_MUTATION = graphql`mutation Login($apiKey: String!) {
login(apiKey: $apiKey) {
token
}
}`;
export default function Authenticator({ apiKey, render }) {
return (
<QueryRenderer query={AUTH_MUTATION} variables={{ apiKey }}
render={render}
/>
);
}
// App.js
import React from 'react';
import Authenticator from './Authenticator';
import MyComponent from './MyComponent';
export default function App({ apiKey }) {
return (
<Authenticator apiKey={apiKey}
render={({ error, props }) => {
if (error) return <div>{error.message}</div>;
if (props) return <MyComponent token={props.loginAPI.token)} />;
return <div>Authenticating...</div>;
}}
/>
);
}
【问题讨论】:
标签: javascript reactjs apollo react-apollo apollo-client