javascript - 使用展开运算符对过滤器数组创建 Firestore 查询
我正在为我的 React 网络应用开发一个过滤器组件,并且想要返回(传递 props)一个用于 Firestore 查询的条件数组。
例如,如果用户想要过滤掉没有评论的帖子,他们会勾选一个复选框,并在过滤器数组中添加 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 错误:扩展参数必须要么具有元组类型,要么传递给剩余参数。TS2556。
我哪里做错了?
答案#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);
