[英]Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. React
I am Facing the Below Mentioned Error When Fetching Data from Firebase and Setting it to State Inside a useEffect
Hook.从 Firebase 获取数据并将其设置为
useEffect
Hook 内的状态时,我useEffect
了useEffect
。
Here is The Code i am Using With Simplified Markup:这是我使用简化标记的代码:
function PostComponent({ id }){
const [post,setPost] = useState({});
const [error,setError] = useState("");
const db = firebase.firestore();
useEffect(()=>{
db.collection('posts').doc(id).get().then(doc=>{
setPost(doc.data());
}).catch(err=>setError(err.message));
}, []);
return (
{error && <h1>{ error }</h1>}
<PostCard data={post} />
);
}
Can you pls try it like this:你能试试这样吗:
//this can be outsite of your component
const db = firebase.firestore();
function PostComponent({ id }){
const [post,setPost] = useState({});
const [error,setError] = useState("");
useEffect(()=>{
db.collection('posts').doc(id).get().then(doc=>{
setPost(doc.data());
}).catch(err=>setError(err.message));
}, [id]);
return (
{error && <h1>{ error }</h1>}
<PostCard data={post} />
);
}
If that doesn't work then the error is probably comming from another component.如果这不起作用,则错误可能来自另一个组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.