如何通过 React Native 从 firebase 中删除数组中的数据?

IT技术 reactjs firebase react-native redux google-cloud-firestore
2021-05-01 13:30:27

我正在使用 React Native 和 Firebase 制作 SNS 应用程序。

我可以在每个帖子的数组中创建评论,并将其显示为 Flatlist。

但我不知道如何删除每条评论。

请让我知道在哪里查看文档或链接。

或者给个提示。(事实上​​,它已经卡在这里将近两个星期了。)

----动作/帖子

export const getComments = (post) => {
  return (dispatch) => {
    dispatch({
      type: "GET_COMMENTS",
      payload: orderBy(post.comments, "date", "desc"),
    });
  };
};

export const addComment = (text, post) => {
  return (dispatch, getState) => {
    const { uid, photo, username } = getState().user;
    let comments = cloneDeep(getState().post.comments.reverse());
    try {
      const comment = {
        comment: text,
        commenterId: uid,
        commenterPhoto: photo || "",
        commenterName: username,
        date: new Date().getTime(),
        postTitle: post.postTitle,
        postDescription: post.postDescription,
        postUser: post.username,
      };
      console.log(comment);
      db.collection("posts")
        .doc(post.id)
        .update({
          comments: firebase.firestore.FieldValue.arrayUnion(comment),
        });
      comment.postId = post.id;
      comment.postTitle = post.postTitle;
      comment.postDescription = post.postDescription;
      comment.postUser = post.username;
      comment.uid = post.uid;
      comment.type = "COMMENT";
      comments.push(comment);
      dispatch({ type: "GET_COMMENTS", payload: comments.reverse() });

      db.collection("activity").doc().set(comment);
    } catch (e) {
      console.error(e);
    }
  };
};

----评论界面

import React from "react";
import styles from "../styles";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
  Text,
  View,
  TextInput,
  FlatList,
  KeyboardAvoidingView,
  TouchableOpacity,
  StatusBar,
  Animated,
  Dimensions,
} from "react-native";
import { addComment, getComments } from "../actions/post";
import moment from "moment";
import "moment/locale/ko";
moment.locale("ko");
import { Swipeable } from "react-native-gesture-handler";

class Comment extends React.Component {
  state = {
    comment: "",
  };

  componentDidMount = () => {
    const { params } = this.props.route;
    this.props.getComments(params);
  };

  postComment = () => {
    const { params } = this.props.route;
    this.props.addComment(this.state.comment, params);
    this.setState({ comment: "" });
  };

  rightActions = (dragX) => {
    const scale = dragX.interpolate({
      inputRange: [-100, 0],
      outputRange: [1, 0.9],
      extrapolate: "clamp",
    });
    const opacity = dragX.interpolate({
      inputRange: [-100, -20, 0],
      outputRange: [1, 0.9, 0],
      extrapolate: "clamp",
    });
    const deleteItem = async (id) => {
      await db.collection("posts").doc(id).delete();
      console.log("Deleted ", id);
    };

    return (
      <TouchableOpacity>
        <Animated.View style={[styles.deleteButton, { opacity: opacity }]}>
          <Animated.Text
            style={{
              color: "white",
              fontWeight: "800",
              transform: [{ scale }],
            }}
            onPress={() => deleteItem(item.id)}
          >
            !!!DELETE COMMENT!!!
          </Animated.Text>
        </Animated.View>
      </TouchableOpacity>
    );
  };

  render() {
    return (
      <View style={styles.container}>
        <StatusBar barStyle="dark-content" />
        <KeyboardAvoidingView
          enabled
          behavior="padding"
          style={[styles.container, styles.marginTop]}
        >
          <FlatList
            keyExtractor={(item) => JSON.stringify(item.date)}
            data={this.props.post.comments}
             renderItem={({ item }) => (
              <View>
                <Swipeable
                  renderRightActions={(_, dragX) => this.rightActions(dragX)}
                >
                  <View style={[styles.row, styles.space]}>
                    <View style={{ margin: 10 }}></View>
                    <View style={[styles.container, styles.left]}>
                      <Text style={styles.marginTop}>
                        <Text style={[styles.bold, styles.grayDark]}>
                          {item.commenterName}
                        </Text>

                        <Text style={styles.gray}>commented</Text>
                      </Text>
                      <Text style={[styles.gray, styles.marginTop5]}>
                        {item.comment}
                      </Text>
                      <Text
                        style={[styles.gray, styles.small, styles.marginTop]}
                      >
                        {moment(item.date).format("ll")}{" "}
                        {moment(item.date).fromNow()}
                      </Text>
                    </View>
                  </View>
                </Swipeable>
              </View>
            )}
          />
          <TextInput
            style={styles.input}
            onChangeText={(comment) => this.setState({ comment })}
            value={this.state.comment}
            returnKeyType="send"
            placeholder="leave comment"
            onSubmitEditing={this.postComment}
          />
        </KeyboardAvoidingView>
      </View>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({ addComment, getComments }, dispatch);
};

const mapStateToProps = (state) => {
  return {
    user: state.user,
    post: state.post,
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Comment);

在此处输入图片说明

2个回答

为了获得数据,您需要从 Firestore 读取数据,修改数组数据,删除所需的值,然后将其保存回数据库 - 这可以在另一篇文章中确认社区在这里

如果您尝试这种方式,您的代码应该如下所示。

const deleteComment = commentText => {
    const userPost = currentUser.Post

    // filter the Comment array
    const newComment = userPost.filter(
        comment => comment.text !== commentText
    )

    // update the doc with the filtered comment
    var userRef = db.collection('post').doc(user.uid)
    userRef.update({
        comment: newComment
    })

    // update my state to reload user data
    setCommentRemoved(true)

}

虽然此代码未经测试,但我相信它是您的应用程序的一个很好的起点。它根据用户和存储评论的帖子删除评论。

除此之外,您可以尝试使用该arrayRemove()功能为您执行此操作。调用该函数的代码将是这样的。

docRef.update({
   comment: FieldValue.arrayRemove('idToRemove');
});

此外,我建议您通过查看 Firestore 开发人员的这篇文章来获取有关如何在 Firestore 中管理和使用数组的更多信息:Cloud Firestore 中的更好的数组!

如果这些信息对您有帮助,请告诉我!

使用 firestore 一次性删除整个 flatlist,

filter data = (_item) => {
    this.setState({ users: this.state.users.filter(item => item. Key=== _item)});
    console.log(this.state.favorites);
}

deleteAllData下面给出的按钮代码中调用此函数

<Touchable Opacity 
        onPress={() => {async function massDeleteUsers() {
            // Get all users
            const usersQuerySnapshot = await firestore().collection('user').get();             
            
            // Create a new batch instance
            const batch = firestore().batch();
            usersQuerySnapshot.forEach(documentSnapshot => { batch.delete(documentSnapshot.ref); });
            return batch.commit();
        }         
        massDeleteUsers().then(() =>{
         this.filterdata();
         console.log('All users deleted in a single batch operation.')})}
         }>