我尝试实现了以下解决方案:
但它们似乎不起作用(请参见下面的代码示例)。 Firestore是否更改了任何内容? 我在下面的代码中弄错了什么吗?
提前感谢!
为了上下文,下面是在React函数组件内useEffect钩子中的代码。 但是,我认为这并不重要,因为没有条件查询的工作示例正常运行。
基本示例 - 硬编码筛选器 - 运行良好。 筛选器已应用
const query = db.collection('todos')
.where('userId', '==', userId)
.where('status', '==', 'pending');
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});
无法正常工作 - 返回具有所有状态的结果。if块内的where查询尚未应用
const query = db.collection('todos').where('userId', '==', userId);
if (filter === 'complete') {
query.where('status', '==', 'pending');
}
if (filter === 'complete') {
query.where('status', '==', 'complete');
}
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});
这是另一个例子,确保 if 代码块本身不是问题所在。创建了一个初始查询,并在 onSnapshot 之前添加了“where”条件。在这种情况下,应用了 userId where 条件,但 status where 条件被忽略了。所有状态为 todo 的都会被返回。
const query = db.collection('todos').where('userId', '==', userId);
query.where( 'status', '==', 'pending' ); // This 'where' clause is being ignored
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});