【问题标题】:Adding Comment to The Post using React, Redux and Firebase使用 React、Redux 和 Firebase 为帖子添加评论
【发布时间】:2021-03-06 14:35:24
【问题描述】:

当我尝试向帖子添加评论时,我收到此错误:

FirebaseError:无法使用空路径调用函数 CollectionReference.doc()。

这是我的代码:

我用这个推送到 Firebase,postId 来自 Redux。

 const postId = useSelector(selectPostId);

  useEffect(() => {
    // za komentiranje na slika
    if (postId) {
      db.collection("posts")
        .doc(postId)
        .collection("comments")
        .orderBy("timestamp", "desc")
        .onSnapshot((snapshot) => {
          setComments(snapshot.docs.map((doc) => doc.data()));
        });
    }
  }, [postId]);

  const postComment = (e) => {
    e.preventDefault();
    db.collection("posts").doc(postId).collection("comments").add({
      text: comment,
      username: user.displayName,
      timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
    setComment("");
  };

这里是 Redux:

export const postSlice = createSlice({
  name: "post",
  initialState: {
    postId: null,
    commentId: null,
  },
  reducers: {
    setPost: (state, action) => {
      state.postId = action.payload.postId;
    },
    setComments: (state, action) => {
      state.commentId = action.payload.commentId;
    },
  },
});

export const { setPost, setComments } = postSlice.actions;

export const selectPostId = (state) => state.post.postId;
export const selectCommentId = (state) => state.post.commentId;

export default postSlice.reducer;

【问题讨论】:

    标签: javascript reactjs firebase redux google-cloud-firestore


    【解决方案1】:

    看起来您向帖子集合传递了错误的文档 ID:

    1. 验证 postId 全局状态是否有值。
    2. 如果 postId 是一个有效值,那么检查帖子集合,看看您是否将正确的 id 传递给正确的集合“数据库架构”

    这就是错误所在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      相关资源
      最近更新 更多