【问题标题】:Delete document by getting document name in Cloud Firestore通过在 Cloud Firestore 中获取文档名称来删除文档
【发布时间】:2018-09-09 19:55:17
【问题描述】:

一直在努力寻找一种方法来使用 React Native 和 Cloud Firestore 删除点击的文档。我想不出一种方法来获取文档 ID,然后在我的代码中使用它来替换 deleteItemId 的值。有任何想法吗?

我的收藏与显示的文档:

我的代码:

componentDidMount(){
    this.getItems();
    const { currentUser } = firebase.auth();
    this.setState({ currentUser });
  }

  getItems = async () => {
    this.setState({ refreshing: true });
    this.unsubscribe = await this.ref.onSnapshot((querySnapshot) => {
          const todos = [];
          querySnapshot.forEach((doc) => {
            todos.push({
              tips: doc.data().tips,
              date: doc.data().date,
              user: doc.data().user,
              like: doc.data().like
            })
          })
          this.setState({
            refreshing: false,
            getData: todos
          })
        })
  }
  deletePost = () => {
     const deleteItemId = "SELECTED DOCUEMNT ID HERE";
     firestore.collection("tips").doc(deleteItemId).delete().then(function() {
          alert("deleted")
      }).catch(function(error) {
          alert("Error removing document: ", error);
      });

  }
  renderItem = ({ item, index }) => {
    let date = item.date;
    return (
      <View style={styles.tips}>
      <View style={styles.wrapper}>
        <View style={styles.profilePicture}>
          <View></View>
        </View>
        <View style={styles.right}>
          <Text style={styles.username}>@{item.user}</Text>
          <Text style={styles.date}>{ moment(item.date).fromNow() }</Text>
        </View>
      </View>
      <Text style={styles.text}>{item.tips}</Text>
      <View style={styles.bar}>
        <Text><Icon onPress={() => this.like()} style={styles.heart} type="Octicons" name="heart" /> {item.like}</Text>
        <Text onPress={() => {
          this.setModalVisible(true);
        }}><Icon style={styles.comment} type="FontAwesome" name="comment-o" />  {item.replies}</Text>
        <Text onPress={() => this.deletePost()}><Icon style={styles.settings} type="Octicons" name="kebab-vertical" /></Text>
      </View>
      </View>
    )
  }

【问题讨论】:

    标签: javascript reactjs firebase react-native


    【解决方案1】:

    每次将 TODO 推送到 todos 时,请确保还包含文档 ID:

    todos.push({
      id: doc.id,
      tips: doc.data().tips,
      date: doc.data().date,
      user: doc.data().user,
      like: doc.data().like
    })
    

    然后在渲染 TODO 时,将 ID 包含在元素的渲染输出中:

    <Text onPress={() => this.deletePost(styles.id)}>
    

    【讨论】:

    • 谢谢!我以前试过这个,但我只得到一个错误。函数 CollectionReference.doc() 要求它的第一个参数是字符串类型,但它是:undefined
    • 这可能是因为我只像这样写:.doc(item.id)。但是我怎么把它写成字符串呢?
    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2018-03-22
    • 2019-04-24
    • 2018-08-02
    • 2021-11-19
    • 2020-12-11
    相关资源
    最近更新 更多