我如何通过React Native从Firebase中删除数组中的数据? [英] how can i remove data in array from firebase by React native?

查看:56
本文介绍了我如何通过React Native从Firebase中删除数组中的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Native& amp;制作SNS应用火力地堡.

I'm making SNS app with React Native & Firebase.

我可以在每个帖子的数组中创建评论,并将其显示为平面列表.

I can create a comments in array of each Post, and show it as a Flatlist.

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

But I don't know how to remove each comment.

请让我知道在哪里检查文档或链接.

Please let me know where to check the document or link.

或者给我一个提示.(实际上,它在这里停留了将近两个星期.)

Or give me a hint. (In fact, it's been stuck here for almost two weeks.)

----动作/发布

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);

推荐答案

要获取数据,您需要从Firestore中读取数据,修改数组数据,删除所需的值,然后保存回到您的数据库-此步骤可以在社区的另一篇帖子中得到确认

For you to achieve data, you will need to read the data from your Firestore, modify the array data, removing the values that you want and then, save it back to your database - this can steps can be confirmed in this other post from the Community here.

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

In case you try this way, your code should be something like this one below.

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)

}

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

While this code is not tested, I believe it's a good starting point for your application. It removes the comment based in the user and the post where the comment is stored.

除此之外,您可以尝试使用

Besides that, you can try use the arrayRemove() function to perform this operation for you. The code for calling the function would be something like this.

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

此外,我建议您通过从以下位置的Firestore开发人员那里查看本文,以获得有关如何在Firestore中管理和使用阵列的更多信息:

In addition, I would recommend you to get more information on how to manage and use arrays in Firestore, by checking this article from a Firestore developer here: Better Arrays in Cloud Firestore!

让我知道信息是否对您有帮助!

Let me know if the information helped you!

这篇关于我如何通过React Native从Firebase中删除数组中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆