简体   繁体   English

React Native 如何获取 Firebase 中特定文档的文档 ID?

[英]How do I get the document ID of a specific document in Firebase on React Native?

I'm working on a project that allows users to write anonymous letters addressed to people by name and I want to add a like/dislike functionality to the app.我正在从事一个项目,该项目允许用户通过姓名写给人们的匿名信件,我想向该应用程序添加喜欢/不喜欢的功能。 I was confused on how to get the specific document ID for that post and also incrementing the likeCount by 1 (in the areas where the "????" are at in the code below)?我对如何获取该帖子的特定文档 ID 以及如何将 likeCount 递增 1 感到困惑(在下面代码中“????”所在的区域)? I want it to update the field "likeCount" in firebase by 1 when the thumbs up icon is pressed.我希望它在按下竖起大拇指图标时将 firebase 中的字段“likeCount”更新为 1。

This is the portion of my code that contains the posts (data from firebase) that is mapped for each firebase document:这是我的代码部分,其中包含为每个 firebase 文档映射的帖子(来自 firebase 的数据):

function Home() {
  const [posts, setPosts] = useState([]);
  const [searchValue, setSearchValue] = useState("");
  const [filteredPosts, setFilteredPosts] = useState([]);
  const collectionRef = collection(db, "posts");

  useEffect(() => {
    const getPosts = async () => {
      const data = await getDocs(collectionRef);
      const filteredRef = query(
        collectionRef,
        where(`recipiant`, "==", `${searchValue}`)
      );

      const querySnapshot = await getDocs(filteredRef);
      let posts = [];
      querySnapshot.forEach((doc) => {
        posts.push(doc.data());
      });
      setFilteredPosts(posts);

      setPosts(
        searchValue
          ? filteredPosts
          : data.docs.map((doc) => ({ ...doc.data() }))
      );
    };

    getPosts();
  }, [searchValue, filteredPosts]);

  return (
    <ImageBackground source={image} style={styles.image}>
      <SafeAreaView style={styles.container}>
        <ScrollView>
          <View style={styles.header}>
            <Text style={styles.title}>Home</Text>
          </View>
          <Pressable>
            <Input
              placeholder="Search for a name"
              inputContainerStyle={styles.searchbar}
              inputStyle={styles.searchInput}
              placeholderTextColor="gray"
              onChangeText={(text) => setSearchValue(text)}
            />
          </Pressable>
          {posts.map((post, key) => {
            return (
              <View style={styles.postWrapper} key={key}>
                <View style={styles.btnWrapper}>
                  <View style={styles.likeBtn}>
                    <Icon
                      name="thumbs-up"
                      size={25}
                      color="#fff"
                      onPress={() => {
                        const postRef = doc(db, "posts", `????`);
                        updateDoc(postRef, {
                          likeCount: ????,
                        });
                      }}
                    />
                    <Text style={styles.likeCount}>{post.likeCount}</Text>
                  </View>
                  <Icon
                    name="thumbs-down"
                    size={25}
                    color="#fff"
                    onPress={() => {}}
                  />
                </View>
                <Card
                  containerStyle={{
                    backgroundColor: "rgba( 255, 255, 255, 0.5 )",
                    borderRadius: 50,
                    height: 300,
                    marginBottom: 25,
                    width: 330,
                    backdropFilter: "blur( 20px )",
                    padding: 20,
                  }}
                >
                  <Card.Title style={styles.notepadHeader}>Message.</Card.Title>

                  <View style={styles.center}>
                    <ScrollView>
                      <Text style={styles.notepadText}>
                        To: <Text style={styles.name}>{post.recipiant}</Text>
                      </Text>
                      <Text style={styles.notepadTextLetter}>
                        {post.letter}
                      </Text>
                      <Text style={styles.notepadFooter}>
                        From:{" "}
                        <Text
                          style={{
                            color: "#9e4aba",
                            fontSize: 20,
                          }}
                        >
                          {post.displayName}
                        </Text>
                      </Text>
                    </ScrollView>
                  </View>
                </Card>
              </View>
            );
          })}
        </ScrollView>
      </SafeAreaView>
    </ImageBackground>
  );
}

This is how my Firestore looks like and I want to retrieve the document id in the circle.这就是我的 Firestore 的样子,我想检索圈子中的文档 ID。

我的消防站:

This will give you the particular doc and perform updateDoc query accordingly.这将为您提供特定的文档并相应地执行 updateDoc 查询。

query(collections('collection_name), where(documentId(), '==', 'your_post_id'))

First, you can add the document ID in 'posts' array as shown below:首先,您可以在“posts”数组中添加文档 ID,如下所示:

const posts = querySnapshot.docs.map((d) => ({ id: d.id, ...d.data() }));
setFilteredPosts(posts);

Then you can read post ID when required:然后您可以在需要时阅读帖子 ID:

<Icon
  name = "thumbs-up"
  size = {25}
  color = "#fff"
  onPress = {() => {
    const postRef = doc(db, "posts", post.id);
    updateDoc(postRef, {
      likeCount: ?? ?? ,
    });
  }
}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM