如何使用适用于 React-Native 的 AWS AppSync 开发工具包动态设置查询参数

How to dynamically set query parameters with AWS AppSync SDK for React-Native

背景: 我正在使用 react-native 构建一个移动应用程序,并且正在设置 AWS 的 AppSync 以将应用程序与云数据源同步。

挑战:我有一个显示列表中所有项目的视图。列表的 ID 作为 prop 传递给组件。我需要使用该列表 ID 来查询该列表的项目。如果我对列表 ID 进行硬编码,我的查询工作正常,但是我很难弄清楚如何在 props 更新时为查询动态设置列表 ID。

这是我在 ListPage 组件中的工作(使用硬编码 ID testList01):

const getListItems = id => gql`
    query getListItems {
      getListItems(listID: ${id}) {
        reference_id,
        quantity,
      }
    }
  `;

export default graphql(getListItems('testList01'), { 
  options: {
    fetchPolicy: 'cache-and-network',
  },
  props: props => ({
    listItems: props.data ? props.data.getListItems : [],
    data: props.data,
  }),
})(withNavigationFocus(ListPage));

我希望能够根据从 props 传入的列表 ID 动态设置要查找项目的列表。具体来说,我正在使用 react-navigation 进入 ListPage,这是一个用户可以在其中查看列表中项目的视图。下面是当用户单击列表名称并路由到 ListPage 组件时执行的代码:

  handleListSelection(list: Object) {
    const { navigation, userLists } = this.props;
    navigation.navigate('ListPage', {
      listID: list.record_id,
      listName: list.list_name,
      userLists,
    });
  }

从我之前的 (pre-AppSync/GraphQL) 实现中,我知道我可以通过 this.props.navigation.state.params.listID 访问 ListPage 中的列表 ID。我希望能够在我的 AppSync 查询中使用它,但是因为查询是在组件外部创建的,所以我无法访问道具,因此我很难获得 ID。

它应该像这样工作:

const getListItems = (id) => {
  return gql`
    query getListItems {
      getListItems(listID: ${id}) {
        reference_id,
        quantity,
      }
    }
  `;
} 

像下面这样调用这个 getListItems

export default graphql(getListItems(id), { //from where ever you want to send the id
  options: {
    fetchPolicy: '
    ......

我没有测试过这段代码。如果可行,请更新。虽然我很确定它有效。

使用一个名为 react-apollo-dynamic-query 的包来完成这项工作,我发现 here. The author of that package also links directly to a simple function 可以完成我在这里尝试做的事情。 本质上,它只是以一种简单的方式包装了常规的 graphql 调用,暴露了 props,以便它们可以传递给查询。

我的代码现在看起来像这样(我在同一文件中对 ListPage 组件的定义下方):

const getListItems = props => {
   const listID = props.navigation.state.params.listID;
   return gql`
      query getListItems {
        getListItems(listID: "${listID}") { // Note the variable being wrapped in double quotes
          reference_id,
          quantity,
         }
       }
   `;
};

const config = {
  options: {
    fetchPolicy: 'cache-and-network',
  },
  props: props => ({
    listItems: props.data ? props.data.getListItems : [],
  }),
};

const MyApolloComponent = graphqlDynamic(getListItems, config)(ListPage);

export default MyApolloComponent;