【问题标题】:Callback onLoad for React-Apollo 2.1React-Apollo 2.1 的回调 onLoad
【发布时间】:2023-03-21 21:21:02
【问题描述】:

我想知道在 Apollo <Query> 组件完成加载时处理设置父母状态的最佳方法是什么?我有一个有时需要查询的 id。我想知道处理这种情况的最佳方法是什么?

目前我有它,子组件将在其中侦听道具更改,如果我注意到我正在寻找更改的数据的道具,我将调用一个函数来更新状态。

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

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

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() {
    ...
  }
}

【问题讨论】:

    标签: reactjs react-apollo


    【解决方案1】:

    您可以从 apollo 导出使用 HoC 包装的子项

    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(),这将返回承诺,您可以链接then() 方法。

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-03
      • 1970-01-01
      • 2017-12-27
      • 2020-07-07
      • 2019-01-26
      • 1970-01-01
      相关资源
      最近更新 更多