Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我一直在试图弄清楚如何创建一个清除函数,因为我不断地得到一个错误_Reactjs_Firebase_Firebase Realtime Database_Use Effect - Fatal编程技术网

Reactjs 我一直在试图弄清楚如何创建一个清除函数,因为我不断地得到一个错误

Reactjs 我一直在试图弄清楚如何创建一个清除函数,因为我不断地得到一个错误,reactjs,firebase,firebase-realtime-database,use-effect,Reactjs,Firebase,Firebase Realtime Database,Use Effect,我正试图找出如何创建一个清理功能,因为我不断收到一个错误,如果我从useEffect依赖项中删除注释,错误就会消失,但是应用程序不会实时更新,这是一个问题。如果有人使用过React和实时数据库,甚至Firestore,对我应该做什么有任何想法,请告诉我 import React, { useContext, useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { toast }

我正试图找出如何创建一个清理功能,因为我不断收到一个错误,如果我从useEffect依赖项中删除注释,错误就会消失,但是应用程序不会实时更新,这是一个问题。如果有人使用过React和实时数据库,甚至Firestore,对我应该做什么有任何想法,请告诉我

import React, { useContext, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'react-toastify';

import User from '../assets/images/user.svg';

import { AuthContext } from '../helpers/firebaseAuth';
import firebase from '../helpers/Firebase';
import Loading from '../helpers/Loading';

export const Comments = ({ match, history }) => {
    const { register, handleSubmit, reset } = useForm();

    const slug = match.params.slug;

    const {...currentUser} = useContext(AuthContext);

    const [comments, setComments] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {

        const fetchData = () => {
            const data = firebase.database().ref(`/posts/${slug}/comments`)

            data.once('value')
            .then((snapshot) => {
                if (snapshot) {
                    let comments = [];
                    const snapshotVal = snapshot.val();
                    for (let comment in snapshotVal) {
                        comments.push(snapshotVal[comment]);
                    }
                    setComments(comments);
                    setLoading(false);
                }
            });
        }
        fetchData();
    }, [slug, comments])


    if (loading) {
        return <Loading />;
    };

    const postComment = (values) => {

        console.log(!!currentUser.currentUser)

        if (!!currentUser.currentUser) {
            const comment = {
                commentText: values.commentText,
                commentCreator: currentUser.currentUser.displayName,
                currentUserId: currentUser.currentUser.uid,
            }

            const postRef = firebase.database().ref(`posts/${slug}/comments`);
            postRef.push(comment);

            reset();
        } else {
            toast.error('You are not authenticated Without seeing the error in question, I can only assume it's because using the following pattern causes an infinite loop because the effect is re-triggered every time 
count
changes:

const [count, setCount] = useState(0);
useEffect(() => setCount(count + 1), [count]);
从“React”导入React,{useContext,useEffect,useState}; 从“react hook form”导入{useForm}; 从'react toastify'导入{toast}; 从“../assets/images/User.svg”导入用户; 从“../helpers/firebaseAuth”导入{AuthContext}; 从“../helpers/firebase”导入firebase; 从“../helpers/Loading”导入加载; 导出常量注释={match,history}=>{ const{register,handleSubmit,reset}=useForm; 常量slug=match.params.slug; const{…currentUser}=useContextAuthContext; const[comments,setComments]=useState[]; const[loading,setLoading]=useStatetrue; useEffect=>{ 常量fetchData==>{ const data=firebase.database.ref`/posts/${slug}/comments` 数据。一次“值” .ThenSapshot=>{ 如果快照{ 让评论=[]; const snapshotVal=snapshot.val; 对于snapshotVal中的let注释{ 注释。pushsnapshotVal[注释]; } 设置注释注释; 设置加载错误; } }; } 获取数据; },[slug,评论] 如果加载{ 回来 }; const postComment=值=>{ console.log!!currentUser.currentUser if!!currentUser.currentUser{ 常量注释={ commentText:values.commentText, commentCreator:currentUser.currentUser.displayName, currentUserId:currentUser.currentUser.uid, } const postRef=firebase.database.ref`posts/${slug}/comments`; postRef.pushcomment; 复位; }否则{
toast.error'如果没有看到问题中的错误,您就没有进行身份验证,我只能假设这是因为使用以下模式会导致无限循环,因为每次计数更改时都会重新触发该效果:

const[count,setCount]=useState0; useEffect=>SetCountCountCount+1[count]; 当你在效果中添加注释时,你也在做同样的事情

要解决此问题,您必须更改效果以依赖Firebase的实时事件来更新注释数组。这可以简单地更改一次“值”。然后将snap=>{…}更改为on“值”,snap=>{…};。由于这现在是一个实时侦听器,您还必须返回一个函数,该函数可以从useEffect调用中取消对侦听器的订阅。正确执行此操作所需的代码量最少为:

const[postId,setPostId]=useState'post001'; useEffect=>{ const postRef=firebase.database.ref'posts'.childpostId; const listener=postRef.on “价值”, postSnapshot=>{ const postData=postSnapshot.val; //…更新用户界面。。。 }, 错误=>{ console.log“获取post失败”,错误; //…更新用户界面。。。 } return=>postRef.off'value',侦听器; },[posted]; 将这些更改应用到您的代码以及一些QoL改进会产生:

const{register,handleSubmit,reset}=useForm; 常量slug=match.params.slug; const{…authContext}=useContextAuthContext;//重命名:currentUser->authContext错误且不明确 const[comments,setComments]=useState[]; const[loading,setLoading]=useStatetrue; 让后处理程序删除后处理程序; useEffect=>{ //不要称此数据为“somethingRef”,它不是数据,而是对它的引用 const postCommentsRef=firebase.database.ref`/posts/${slug}/comments`; //创建实时侦听器 const listener=postCommentsRef.on “价值”, querySnapshot=>{ 让_评论=[]; querySnapshot.forEachcommentSnapshot=>{ const thiscompent=commentSnapshot.val; thisComment.key=commentSnapshot.key;//存储用于删除/编辑操作的密钥 _评论。这个评论; }; setComments_comments; 设置加载错误; }, 错误=>{ log`Error在获取post${slug}`的注释时出错,err; //TODO:句柄错误 }; //更新新注释处理程序 _postCommentHandler=formData=>{ console.log{ isLoggedIn:!!authContext.currentUser }; 如果!authContext.currentUser{
吐司.错误'你没有被认证对不起,如果我没有澄清我正在做的任何事情
作为一个新手,你们中的大多数人可能已经告诉我,请包括你收到的错误消息和它出现的行。看看这篇文章是否也对你有帮助,我确实返回了=>postCommentsRef.off;而不是返回=>postCommentsRef.offlistener;谢谢你的回复samthecodingman,你帮了我很多忙,我甚至没有意识到,我知道我需要帮助,是的,我真的需要在我的代码和命名的东西上工作。再次感谢:啊,那是我的错。它应该是postCommentsRef.off'value',listener;,我建议使用它,因为postCommentsRef.off可能会导致意外的副作用,因为它将取消该位置上的所有侦听器,甚至是组件范围之外的侦听器。