我正在尝试制作一个封装阿波罗客户端查询组件的组件。我使用apollo-link-state进行本地状态管理,我希望有一个错误通知系统,通知用户所有的事情。
我的部件看起来像这样..。
export class Viewer extends React.Component {
static propTypes = {
children: PropTypes.func
};
render() {
const { children } = this.props;
return (
<Query query={GET_VIEWER}>
{({ data, client, error }) => {
if (error) {
client.mutate({
mutation: ADD_NOTIFICATION,
variables: { message: unpackApolloErr(error), type: 'Error' }
});
}
return children(data.viewer ? data.viewer : user);
}}
</Query>
);
}
}但是当它试图用突变来添加错误时,我得到了反应错误。
Warning: forceUpdate(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.我看不出有什么明显的解决办法,而且我也不明白如果客户端被作为渲染工具而不能使用,为什么会发生这种情况.我肯定遗漏了一些简单的东西,但我看不出它是什么
发布于 2018-04-01 07:18:41
结果发现,当使用onError https://www.apollographql.com/docs/link/links/error.html时,客户端在apollo-link-error函数中可作为this使用。
我以前曾尝试使用onError访问客户端,但即使客户机是在onError处理程序之后声明的,调用它的作用域是否确实包含客户端,这并不明显。
// client is available here even though it is defined first
const err = onError({ graphQLErrors }) => {
this.client.mutate({ mutation: ADD_ERROR, variables: { graphQLErrors }})
}
const client = new ApolloClient({
cache,
link: ApolloLink.from([err, httpLink])
})发布于 2018-04-03 06:58:07
之所以会出现Warning: forceUpdate,可能是因为当存在突变时,阿波罗在内部会引起forceUpdate。因此,突变应该在render方法中。
处理阿波罗错误后突变的最佳方法是添加onError链接,如https://www.apollographql.com/docs/react/features/error-handling.html#network中所述。
// Add errorLink into Apollo Client
const errorLink = onError(({ graphQLErrors, networkError, operation }) => {
this.client.mutate({ mutation: ..., variables: {}});
});
const client = new ApolloClient({
cache,
link: ApolloLink.from([err, httpLink])
})https://stackoverflow.com/questions/49583369
复制相似问题