首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React:阿波罗客户端:无法在现有状态转换期间进行更新

React:阿波罗客户端:无法在现有状态转换期间进行更新
EN

Stack Overflow用户
提问于 2018-03-31 01:34:59
回答 2查看 1.2K关注 0票数 1

我正在尝试制作一个封装阿波罗客户端查询组件的组件。我使用apollo-link-state进行本地状态管理,我希望有一个错误通知系统,通知用户所有的事情。

我的部件看起来像这样..。

代码语言:javascript
复制
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>
    );
  }
}

但是当它试图用突变来添加错误时,我得到了反应错误。

代码语言:javascript
复制
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`.

我看不出有什么明显的解决办法,而且我也不明白如果客户端被作为渲染工具而不能使用,为什么会发生这种情况.我肯定遗漏了一些简单的东西,但我看不出它是什么

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-01 07:18:41

结果发现,当使用onError https://www.apollographql.com/docs/link/links/error.html时,客户端在apollo-link-error函数中可作为this使用。

我以前曾尝试使用onError访问客户端,但即使客户机是在onError处理程序之后声明的,调用它的作用域是否确实包含客户端,这并不明显。

代码语言:javascript
复制
// 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])
})
票数 0
EN

Stack Overflow用户

发布于 2018-04-03 06:58:07

之所以会出现Warning: forceUpdate,可能是因为当存在突变时,阿波罗在内部会引起forceUpdate。因此,突变应该在render方法中。

处理阿波罗错误后突变的最佳方法是添加onError链接,如https://www.apollographql.com/docs/react/features/error-handling.html#network中所述。

代码语言:javascript
复制
// 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])
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49583369

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档