为什么这个 React 组件不断重新渲染?



我有这个帖子组件,如果用户在Firebase中输入现有帖子的ID,它就会挂载:

<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中的状态时,这会由于状态更改而触发重新渲染,一旦组件更新,useEffect会再次运行,这会更改触发另一个渲染周期的状态,由于这种模式,您的组件会不断重新渲染。

您可以添加一个依赖项数组,以告知useEffect仅在组件挂载时以及某些内容发生更改时运行,如下所示:

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('');
useEffect((): any => {
const db = fb.firestore();
const ref = db.doc(`posts/${props.match.params.id}`)
ref.get().then((doc: any) => {
if (doc.exists && isMounted.current) {
setPostData(doc.data().content);
setExistingComments(doc.data().comments ? doc.data().comments : [])
}
});
return () => { };
}, [setPostData, setExistingComments]);
// setPostData, setExistingComments won't get a new reference for every render so they won't cause useEffect to run
return (<></>);
}

相关内容

  • 没有找到相关文章

最新更新