简体   繁体   English

为什么这个 React 组件一直在重新渲染?

[英]Why does this React component keep re rendering?

I have this Post component which mounts if the user types in the Id of an existing post in firebase:如果用户在 firebase 中输入现有帖子的 ID,我将安装此 Post 组件:

<Route path='/posts/:id' component={Post} />

However, console logging this component sends back the log indefinitely causing my browser and actions on the page to be really slow.但是,控制台记录此组件会无限期地发回日志,导致我的浏览器和页面上的操作非常慢。

Heres the content of the Post component, I think it's something to do with the way I'm setting the state in useEffect but I'm not sure how to fix it.这是 Post 组件的内容,我认为这与我在 useEffect 中设置 state 的方式有关,但我不确定如何修复它。 I've tried React.Memo and that didn't work:我试过 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

Thanks in advance for your help:)在此先感谢您的帮助:)

When you're updating the state inside useEffect , this triggers a rerender because of the state change and once the component updates, useEffect runs again which changes the state triggering another render cycle, because of this pattern your component keeps rerendering. When you're updating the state inside useEffect , this triggers a rerender because of the state change and once the component updates, useEffect runs again which changes the state triggering another render cycle, because of this pattern your component keeps rerendering.

You can add a dependency array to tell useEffect to run only when the component mounts and also when something changes, like this:您可以添加一个依赖数组来告诉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 (<></>);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么我的反应组件不断重新渲染? - Why does my react component keep re-rendering? 为什么我的组件没有在响应中重新渲染 - why my component is not re-rendering in react React 在重新渲染父组件时如何重用子组件/保留子组件的 state? - How does React re-use child components / keep the state of child components when re-rendering the parent component? 当props进入组件时,为什么我的react组件没有重新渲染? - Why is my react component not re rendering when props comes into the component? 为什么当我将@action 装饰器添加到反应事件处理程序 function 时组件不重新渲染 - Why does the component is not re-rendering when i add @action decorator to an react event handler function 在 state 挂钩中更新 object 时,React 组件不会重新渲染 - React Component does not re rendering when updating an object in state hooks 在 React 功能组件中重新渲染 - 为什么会出现这种行为? - Re-rendering in React functional component - why this behavior? 重新渲染React组件 - re-rendering React Component 重新渲染组件React - re-rendering a component React 什么是正确的方法来保持使用setTimeout来重新渲染组件,直到react js中的prop更改 - what is the right way to keep re-rendering component using setTimeout until prop changes in react js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM