【发布时间】:2020-10-25 22:28:02
【问题描述】:
如果用户在 firebase 中输入现有帖子的 ID,我会安装这个 Post 组件:
<Route path='/posts/:id' component={Post} />
但是,控制台记录此组件会无限期地发回日志,导致我的浏览器和页面上的操作非常缓慢。
这是 Post 组件的内容,我认为这与我在 useEffect 中设置状态的方式有关,但我不确定如何修复它。我试过 React.Memo 并没有用:
function Post(props: RouteComponentProps<PostParams>) {
const [postData, setPostData] = useState({ title: '', body: '', author: '', time: 0, photoURL: '', likes: 0, dislikes: 0});
const [existingComments, setExistingComments] = useState([])
const [commentContent, setCommentContent] = useState('');
const isMounted = useRef(false);
const db = fb.firestore();
const ref = db.doc(`posts/${props.match.params.id}`)
useEffect(():any => {
isMounted.current = true;
ref.get().then((doc: any) => {
if(doc.exists && isMounted.current) {
setPostData(doc.data().content);
setExistingComments(doc.data().comments ? doc.data().comments : [])
}
});
return ()=> isMounted.current = false;
});
return (
//... some html that displays the information I've got from firebase
提前感谢您的帮助:)
【问题讨论】:
-
在
useEffect之前添加[])
标签: javascript reactjs components react-hooks