首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React-Apollo 2.1的回调onLoad

React-Apollo 2.1的回调onLoad
EN

Stack Overflow用户
提问于 2018-04-03 23:34:15
回答 1查看 542关注 0票数 0

我想知道当Apollo <Query>组件完成加载时,设置父组件状态的最佳方式是什么?我有一个id,有时我必须查询它。我想知道处理这件事的最好方法是什么?

现在我有了它,其中的子组件将监听prop的变化,如果我注意到我正在寻找的数据的prop发生了变化,我会调用一个函数来更新状态。

有没有一种更好的方法来处理这个问题,而不需要子组件监听更新?

这是我目前正在做的伪代码

代码语言:javascript
复制
import * as React from 'react';
import { Query } from 'react-apollo';

class FolderFetcher extends React.Component<Props, { id: ?string}> { 
  constructor(props) {
    super(props);
    this.state = {
      id: props.id
    }
  }

  setId = (id) => {
    this.setState({ id });
  };

  render() {
    const { id } = this.props;

    return (
      <Query skip={...} query={...}>
        ((data) => {
          <ChildComponent id={id} newId={data.id} setId={this.setId} />
        })
      </Query>
    );
  }
}

class ChildComponent extends React.Component<Props> {
  componentDidUpdate(prevProps) {
    if (prevProps.newId !== this.props.newId && 
        this.props.id !== this.props.newId) {
      this.props.setId(this.props.newId);
    }
  }
  render() {
    ...
  }
}
EN

回答 1

Stack Overflow用户

发布于 2018-04-04 00:30:16

您可以从apollo中导出子组件作为与HoC封装的组件

代码语言:javascript
复制
import { graphql } from 'react-apollo'

class ChildComponent extends React.Component {
  // inside props you have now handy `this.props.data` where you can check for `this.props.data.loading == true | false`, initially it's true, so when you will assert for false you have check if the loading was finished. 
}

export default graphql(Query)(ChildComponent)

另一种选择是手动获取客户端,然后运行client.query(),它将返回promise,您可以为then()方法链接。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49633933

复制
相关文章

相似问题

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