如何使用动态输入从 Firestore 查询数据

Ton*_*Bui 0 javascript firebase reactjs google-cloud-firestore

我的代码有问题,我不知道如何以正确的方式解决它。

我正在尝试编写一个过滤器,当用户单击每个过滤器时,它会自动从 Firestore 查询数据。

在此处输入图片说明

在我的 Redux Saga 中有这个:

const {type, currency, location} = action.payload;
Run Code Online (Sandbox Code Playgroud)

一切正常,但问题是当我尝试使用动态输入查询数据时:例如:

firebase
        .firestore()
        .collection("ItemData")
        .where("type", "==", type)
        .where('currency', '==', currency)
        .where('location', '==', location)
Run Code Online (Sandbox Code Playgroud)

当用户单击选项时,type它不显示任何输入currency并且location没有数据,只有空字符串,因此查询返回无响应。除非您单击所有过滤器,否则它将显示正确的响应。

那么我该如何解决这个问题呢?

Fra*_*erZ 6

您应该只在需要时添加到查询子句中(即类型、货币或位置为真/非空):

let query = firebase
    .firestore()
    .collection("ItemData");

if (type) {
    query = query.where('type', '==', type);
}

if (currency) {
    query = query.where('currency', '==', currency);
}

if (location) {
    query = query.where('location', '==', location);
}
Run Code Online (Sandbox Code Playgroud)

特别感谢这篇与你有类似问题的帖子