【问题标题】:Apollo boost trigger refetch outside of componentApollo boost 触发器在组件之外重新获取
【发布时间】:2018-08-31 22:23:40
【问题描述】:

我在 React (web) 中使用 Apollo 的新 apollo-boost,我想知道两件事:a) 为什么 Apollo 不自动重新获取变量更改的数据和 b) 如何在外部调用 refetch Query 组件?

在我的特定用例中,我需要从父组件的状态传递某些过滤器。考虑以下代码:

class GalleryPage extends Component {
  constructor () {
    super();
    this.state = {
      filters:           {
        brands:    [1, 3],
        filetypes: [4, 5, 6],
      },
    };
  }

  render() {
    return (
      <div>
        <Query query={FilesQuery} variables={this.state.filters}>
          {result => (result.networkStatus === 7 ? result.data.files.map(file => <div>{file.name}</div>) : '')}
        </Query>
      </div>
    );
  }
}

this.state.filters 更改时,我希望 Apollo 重新获取数据。但由于这不起作用,我正在尝试致电refetch。我可以通过从数据中解构它并调用它来调用refetch&lt;button type="button" onClick={() =&gt; refetch()}&gt;Refetch&lt;/button&gt;。显然,这在组件之外是行不通的。而且我不知道如何在组件之外调用它。我觉得事件系统在这里可能会有所帮助,但我不确定这是否是正确的方法。

提前致谢!

【问题讨论】:

    标签: reactjs react-apollo


    【解决方案1】:

    示例代码中的问题似乎是嵌套对象似乎不会触发重新获取。所以,为了触发重新获取,我所做的是改变状态的组织:

    // Instead of
    this.state = {
      filters: {
        brands: [1, 3],
        filetypes: [4, 5, 6],
      }
    }
    
    // I'm now doing
    this.state =  {
      filteredBrands: [1, 3],
      filteredFiletypes: [4, 5, 6]
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2020-10-22
      • 2019-11-30
      • 2017-03-20
      • 2021-04-19
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多