Внимание: У React Hook useEffect отсутствует зависимость: «postImage». Либо включите его, либо удалите массив зависимостей во время сборки npm

#javascript #reactjs

#язык JavaScript #реагирует на

Вопрос:

В моем проекте всякий раз, когда я запускаю npm, запускаю команду сборки, она выдает предупреждающее сообщение: Предупреждение: У React Hook useEffect отсутствует зависимость: «postImage». Либо включите его, либо удалите массив зависимостей. реагируйте-крючки/исчерпывающие-депы. Как это исправить. Заранее спасибо. Вот мой полный код, в котором я получаю это сообщение.

 import Image from 'next/image'; import {useRef} from 'react'; import { useSession } from "next-auth/client"; import {ChatAltIcon,ThumbUpIcon,ShareIcon} from "@heroicons/react/outline"; import{LoveIcon,SadEmojiIcon} from "@heroicons/react/solid"; import InsertEmotionIcon from "@material-ui/icons/InsertEmoticon" import SentimentVeryDissatisfiedIcon from "@material-ui/icons/SentimentVeryDissatisfied"; import FavoriteIcon from "@material-ui/icons/Favorite"; import MoodIcon from "@material-ui/icons/Mood"; import MoodBadIcon from "@material-ui/icons/MoodBad"; import firebase from 'firebase'; import { db, storage } from "../firebases"; import {useEffect,useState} from 'react'; import {useCollection} from "react-firebase-hooks/firestore"; import "react-responsive-carousel/lib/styles/carousel.min.css"; // requires a loader import { Carousel } from 'react-responsive-carousel'; const Post=({id,name,message,email,timestamp,postImage})=gt;{  const commentRef=useRef(null);  const [isShown, setIsShown] = useState(false);  const [session]=useSession();  const[totalImage,setTotalImage]=useState(null);  const[load,setLoaded]=useState(false);  const likePost= async(e)=gt;{  let min =1;  let max = 50;  let postId = e.target.getAttribute("id");  console.log(postId)  let userId = (Math.floor(Math.random()*(max-min 1)) min);  let reaction = e.target.getAttribute("data-reaction");  let item = {postId,userId,reaction};  console.log(reaction);  let send = await fetch("http://localhost:8000/api/backend",{  method:'post',  body:JSON.stringify(item),  headers:{  "Content-Type":'application/json',  "Accept":'application/json'  },  }).then(response=gt;{  console.log(response)  })  }  const[user,loading,error] = useCollection(  db.collection("users").orderBy("joined_at","desc")  );  const submitComment=async(e)=gt;{  if (!commentRef.current.value) return;  else  {  console.log("comment")  }    }  const handleEvent=(e)=gt;{  if(e.detail==2){  setIsShown(true)  }  else{  setIsShown(false)  }  }  useEffect(()=gt;{  const remainingImage=totalImage gt; 6 ? totalImage-6:0;   },[remainingImage])  return (  lt;div className="flex flex-col"gt;  lt;div className="p-5 bg-white mt-5 router-t-2xl shadow-sm"gt;  lt;div className="flex items-center space-x-2"gt;  lt;divgt;  lt;p className="font-medium"gt;{name}lt;/pgt;  {  timestamp? lt;p className="text-xs text-gray-40"gt;{timestamp}lt;/pgt; :(  lt;p className="text-xs text-gray-40"gt;Loading...lt;/pgt;  )  }   lt;/divgt;  lt;/divgt;  lt;p className="pt-4"gt;{message}lt;/pgt;  lt;/divgt;   lt;div className="relative h-56 bg-white"gt;   {/* lt;div className="grid-cols-3 p-20 space-y-2 lg:space-y-0 lg:grid lg:gap-3 lg:grid-rows-3"gt; */}  lt;Carouselgt;  {  useEffect(()=gt;{  postImage?.map((ele)=gt;{  return ele.map((urls)=gt;{  setTotalImage(urls.url.length);  return urls.url.map((url_,index)=gt;{  return lt;div key={index} className="w-full rounded"gt;lt;Image src={url_} layout="fill" objectFit="cover"alt="image"/gt;lt;/divgt;  })   })  })    },[session])    }  {/* lt;/divgt; */}  lt;/Carouselgt;  lt;/divgt;  {  isShown amp;amp;(  lt;div className="flex justify-start items-center bg-white" gt;  lt;div className=" items-center px-1 p-2 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;FavoriteIcon onClick={()=gt;setIsShown(false)}className="text-red hover:text-red-500"style={{color:"red"}}gt;lt;/FavoriteIcongt;  lt;/divgt;  lt;div className=" items-center p-2 px-1 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;InsertEmotionIcon onClick={()=gt;setIsShown(false)}className="text-yellow hover:text-yellow-500" style={{color:"yellow"}}gt;lt;/InsertEmotionIcongt;  lt;/divgt;  lt;div className=" items-center p-2 px-1 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;SentimentVeryDissatisfiedIcon onClick={()=gt;setIsShown(false)} className="text-yellow hover:text-yellow-500"style={{color:"yellow"}}gt;lt;/SentimentVeryDissatisfiedIcongt;  lt;/divgt;  lt;div className="items-center p-2 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;MoodIcon onClick={()=gt;setIsShown(false)} className="text-yellow hover:text-yellow-500" style={{color:"yellow"}}gt;lt;/MoodIcongt;  lt;/divgt;  lt;div className=" items-center px-1 -1 p-2 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;MoodBadIcon onClick={()=gt;setIsShown(false)} className="text-yellow hover:text-yellow-500"style={{color:"yellow"}}gt;lt;/MoodBadIcongt;  lt;/divgt;  lt;/divgt;  )  }  lt;div className="flex justify-between items-center bg-white shadow-md text-gray-700 border-t mt-5"gt;  lt;div onDoubleClick={handleEvent} className="flex items-center hover:bg-gray-100 flex-grow justify-content p-2 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;ThumbUpIcon className="text-lg sm:text-base h-5 corsor-pointer"onClick={likePost} id={id} data-reaction="like" gt;lt;/ThumbUpIcongt;  lt;span className="cursor-pointer text-2xl text-gray-700"gt;1223lt;/spangt;  lt;/divgt;  lt;div className="flex items-center hover:bg-gray-100 flex-grow justify-content p-2 rounded-xl corsor-pointer rounded-none"gt;  lt;ChatAltIcon className="text-lg sm:text-base h-5 corsor-pointer"gt;lt;/ChatAltIcongt;  lt;span className="cursor-pointer text-2xl text-gray-700"gt;7777lt;/spangt;  lt;/divgt;  lt;div className="flex items-center hover:bg-gray-100 flex-grow justify-content p-2 rounded-xl corsor-pointer rounded-none rounded-bl-2xl"gt;  lt;ShareIcon className="text-lg sm:text-base h-5 corsor-pointer"gt;lt;/ShareIcongt;  lt;span className="cursor-pointer text-2xl text-gray-700"gt;312lt;/spangt;  lt;/divgt;  lt;/divgt;  lt;div className="flex space-x-4 p-4 py-1 items-center bg-white "gt;  {session ? lt;gt;lt;Image src={session.user.image} height={40} width={40} layout="fixed"className="rounded-full"alt="image"/gt; lt;/gt;:null  }  lt;form className="flex flex-1"gt;  lt;input className="rounded-full h-12 bg-gray-100 flex-grow px-5 focus:outline-none" ref={commentRef} type="text"placeholder="Comment..."/gt;  lt;button hidden type="submit"onClick={submitComment}gt;lt;/buttongt;  lt;/formgt;  lt;/divgt;  lt;div className="rounded-b-2xl bg-white flex text-gray-40 pb-2 pl-4 "gt;  lt;small className="mx-auto"gt;Press enter to submit your comment.lt;/smallgt;  lt;/divgt;  lt;/divgt;  ) } export default Post;  

Ответ №1:

Ты можешь :

  1. Используйте // eslint-отключить-реагирование на следующую строку-крючки/исчерпывающие-депы в верхней части строки, вызывающие ошибку
  2. Отключите это правило eslint в .eslintrc.json
  3. Просто включите отсутствующую переменную в массив зависимостей useEffect ( [session, postImage] )