【问题标题】:Using the spread operator on an array of filters to create a Firestore query在过滤器数组上使用扩展运算符创建 Firestore 查询
【发布时间】:2021-11-09 20:10:09
【问题描述】:

我正在为我的 React Web 应用程序开发一个过滤器组件,并希望返回(通过 props)一组用于 Firestore 查询的条件。

例如,如果用户想要过滤掉没有 cmets 的帖子,他们会选中一个复选框并将 where("commentsCount", ">", "0") 添加到过滤器数组中。

  const queryParams = [
    collection(db, "posts"),
    orderBy(sortType, sortMethod),
    limit(POSTS_PER_PAGE),
  ];
  const filters = [
    where("commentsCount", ">", "0"),
    // And possibly more where's
  ];
  queryParams.push(...filters);
  
  // Create a firestore query object using the parameters
  const _query = query(...queryParams);

但是这样做会给我一个 TypeScript 错误:A spread argument must either have a tuple type or be passed to a rest parameter. TS2556

我做错了什么?

【问题讨论】:

  • 看看stackoverflow.com/questions/4156101/…,您想要一个连接queryParamsfilters 的新数组,而不是仅仅推送它。
  • @iunfixit 连接 queryParams 和过滤器不是问题。我的问题是当我尝试在查询构造函数中使用扩展运算符时出现 TypeScript 错误。

标签: javascript reactjs typescript firebase google-cloud-firestore


【解决方案1】:

您不能在query 中传递(CollectionReference<DocumentData> | QueryConstraint)[] 类型的参数。尝试直接在query 中添加collection() 并将其从queryParams 中删除,这样它将是QueryContraint[] 类型的数组:

const queryParams = [
  orderBy(sortType, sortMethod),
  limit(POSTS_PER_PAGE),
];

const filters = [
  where("commentsCount", ">", "0"),
  // And possibly more where's
];
  
// Create a firestore query object using the parameters
const _query = query(collection(db, "posts"), ...queryParams);

【讨论】:

  • 我连接数组的方法似乎不是问题。如果我使用您的解决方案,我会得到与原始帖子完全相同的错误。
  • @Vid 你可以重新启动打字稿服务器并尝试吗?您还可以分享错误的屏幕截图吗?
  • 这里是错误i.imgur.com/Ct2SXOd.png的截图
  • @Vid 现在我很好奇 query 定义在哪里。你能分享那个完整的文件以便我们看到导入吗?
  • 您更新的答案有效。谢谢您的帮助。我将您的答案标记为解决方案。
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 2014-10-25
  • 2017-03-16
  • 2016-06-12
  • 2012-10-09
相关资源
最近更新 更多