【发布时间】:2018-09-02 07:51:58
【问题描述】:
新的 Apollo Client 2.1 使用渲染道具模式而不是 HoC 模式,因此它稍微改变了查询和突变的处理方式。
我已经开始使用它,但不确定一些基本的东西。一是错误处理。我有一个自定义的“AuthResponse”组件,我想传递成功或错误响应。如果在我使用 React 的本地组件状态将错误传递给我的 AuthResponse 组件时出现错误(或成功),但我不确定这是否是最好的方法?
<View style={styles.homeContainer}>
// this is where I want to pass the error to. Currently uses React component state but I'm not sure if this is the best way?
<AuthResponse
authResponse={(this.state && this.state.authResponse) || null}
/>
<Mutation
mutation={registerMutation}
update={(cache, { data: { registerUser } }) => {
// user has been registered
}}
onError={error => {
// is this the right place to start passing errors to other components?
this.setState({
authResponse: error
});
}}
>
{(registerUser, { data, error }) => (
<View>
<Formik
onSubmit={(
values,
{ setSubmitting, setErrors /* setValues and other goodies */ }
) => {
registerUser({ variables: { ...values } });
}}
render={({
handleSubmit
}) => (
<View>
<Button
onPress={handleSubmit}
/>
</View>
)}
/>
</View>
)}
</Mutation>
<Text onPress={this.goToLogin}>Login</Text>
</View>
我在这里假设 Mutation 组件应该尽可能小 - 即不要包裹整个页面,因为屏幕上的不同区域可能需要来自 Query 或 Mutation 组件的不同数据。
我确实考虑使用 Apollo Client 的 Query 组件包装 AuthResponse 组件,从本地缓存中查询数据,我将手动更新这些数据。这似乎是一个更好的解决方案,但文档中没有关于如何在页面/屏幕周围传播多个查询/突变组件的任何内容。
谢谢
【问题讨论】:
-
v2.1 添加
Query和Mutation组件在我看来只是丑(代码味道)。但好消息是,您仍然可以像以前一样编写 2.1 之前的版本并编写 HOC。 -
是的,我完全同意!特别是当文档说要嵌套组件以组合它们时。这似乎很奇怪。我在 HoC 上做这件事的唯一问题是我需要文档,这些文档已经更改为新的 2.1 版本。
-
哦,很多人似乎也有同感:medium.com/@peggyrayzis/hi-emmanuel-6b989f5180e2
标签: reactjs react-native react-apollo apollo-client