首页 > 解决方案 > 在 useEffect 中使用“array-contains”的 react-native-firebase 查询不断刷新组件

问题描述

我只是试图发出请求以仅获取包含当前用户 ID 的线程。

如果我删除我的“where”查询,我可以获取所有线程。

有我的代码:

useEffect(() => {
    const unsubscribe = firestore()
      .collection('THREADS')
      // query is empty
      .where('usersIds', 'array-contains', ['60ddd70c7a3a1e8e62d14dac'])
      .orderBy('latestMessage.createdAt', 'desc')
      .onSnapshot(querySnapshot => {
        const threadsQueried = querySnapshot
          ? querySnapshot.docs.map(documentSnapshot => {
              return {
                ...documentSnapshot.data(),
              };
            })
          : null;

        setThreads(threadsQueried);

        if (loading) {
          setLoading(false);
        }
      });

    return () => unsubscribe();
  });

我已经尝试过不将我的 id 放入数组中,但组件不断刷新,如下所示:

.where('usersIds', 'array-contains', '60ddd70c7a3a1e8e62d14dac')

我的火力基地数据:

火力基地

我已经在这里检查了https://stackoverflow.com/a/59053018/9300663

在这里https://stackoverflow.com/a/59215461/9300663

编辑:所以当 id 在查询中没有括号('60ddd70c7a3a1e8e62d14dac')时它可以工作

但我的组件不断刷新。

如果我向我的 useEffect 添加一个空数组或一个具有依赖关系的数组,则查询不再起作用。

编辑2:查询正在工作,但被调用了两次,第二次返回'null',这正在清空我的状态。

有和没有'where'查询

标签: javascriptfirebasereact-nativereact-native-firebase

解决方案


因此,当我尝试使用 get() 而不是 onSnapshot() 获取 Firebase 查询的另一种方法时,我找到了解决方案:

firestore()
      .collection('THREADS')
      .where('usersIds', 'array-contains', user.id)
      .orderBy('latestMessage.createdAt', 'desc')
      .get()
      .then(querySnapshot => {
        const threadsQueried = querySnapshot.docs.map(documentSnapshot => {
          return {
            ...documentSnapshot.data(),
          };
        });
        setThreads(threadsQueried);

'get()' 的问题是查询只工作一次,并且在创建新线程时不会更新。

但它让我有一个 Firebase 错误,要求我创建索引:“usersIds”和“latestMessage.createdAt”。创建它们之后,我能够重用我的旧代码并且现在一切正常。

useEffect(() => {
    const unsubscribe = firestore()
      .collection('THREADS')
      .where('usersIds', 'array-contains', user.id)
      .orderBy('latestMessage.createdAt', 'desc')
      .onSnapshot(querySnapshot => {
        const threadsQueried = querySnapshot.docs.map(documentSnapshot => {
          return {
            ...documentSnapshot.data(),
          };
        });
        setThreads(threadsQueried);
      });

    return () => unsubscribe();
  }, []);

推荐阅读