【问题标题】:React - Apollo, how to put Object inside the query?React - Apollo,如何将 Object 放入查询中?
【发布时间】:2018-05-26 12:56:54
【问题描述】:

我正在研究搜索功能。在输入更改时会发生一些事情,我得到数组数组: pages level 1 [1,17] pages level 2 [15] pages level 3 [16]

我想要的是从该数组创建特定的页面对象(这不是问题)并将其放入 Apollo 查询中,如下所示:

folders(search: [...some conditions]) {
data {
  id
  title

  pages(search: [{field: "id", value: "1"}, {field: "id", value: "17", type: OR}]) {
    data {
      id
      title
      pages(search: [{field: "id", value: "15"}]) {
        data {
          id
          title
          pages(search: [{field: "id", value: "16"}]) {
            data {
              id
              title
            }
          }
        }
      }
    }
  }
}
}

这就是我卡住的地方!我不能使用纯 Apollo 变量,因为我不知道这棵页面树有多深,而且我认为 Apollo 不允许我在查询中做一些循环。

我认为我必须在我的组件中创建这个对象,因为我还可以将它保存到 Redux 存储中。

我做了类似的东西:

const thePages = SearchInTree.createQueryFragmentWithPages();
const ACCURATE_SEARCH_QUERY = gql`
  query SecondSearch{folders(search: [...some conditions]) {
    data {
      id
      title

      ${thePages}
    }
  }
}

where thePages - 我的组件类的静态方法(我将在其中创建所需的对象或字符串)的结果。但在这种情况下,我遇到了另一个问题 - Apollo 不想在我的静态文件中看到任何变化,因为查询位于我的班级之外。

我还尝试将此逻辑取出到单独的组件中,然后从 Redux 存储中提取数据。但是我不知道如何将此组件插入到我的查询中。

我知道我错过了什么,也许是另一种方式,我不知道...... 请帮忙!

【问题讨论】:

    标签: reactjs apollo react-apollo


    【解决方案1】:

    我最终通过使用 withApollo HOC 解决了这个问题。 我给新手简短的说明:)

    import {compose, gql, withApollo} from 'react-apollo';
    ...// some imports
    
    class TestClass extends React.Component {
        ...// some code
    
        let queryString = `folders{data{id, pages}}`;
    
        this.props.client.query({
          query: gql `query TestQuery{${queryString}}`,
          variables: someVar,
    
        }).then((data) => {
          console.log('then', data, this.props);
          // here you can also save result to the Redux store
    
        }).catch((err) => {
          console.log('catch', err)
        });
    }
    ...
    export default withApollo(TestClass);
    

    如您所见,可以构建一些复杂的东西并将其传递给查询。当然,您可以将此查询定义包装在一个函数中并将其委托给某个事件,例如点击。

    享受你的编码;)

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2016-05-05
      • 2020-10-22
      • 2019-06-02
      • 2021-07-04
      • 2021-08-05
      • 2016-11-30
      • 1970-01-01
      • 2017-10-08
      相关资源
      最近更新 更多