简体   繁体   English

React 避免在重新渲染后重新调用函数

[英]React avoid re-calling functions after re-render

In my functional component, I have a useState variable:在我的功能组件中,我有一个 useState 变量:

const [locations, setLocations] = React.useState([]);

, I'm using useEffect to create a viewer in a div container, this viewer change locations values, ,我正在使用 useEffect 在 div 容器中创建一个查看器,这个查看器更改locations值,

    useEffect(()=>{
        const container = document.getElementById('viewer');
        Viewer.setContainer(container);
        Viewer.onUpdate(locations => {
          setLocations(locations);
          });
        }
       })

After that I'm showing the Viewer as well as the locations values in the return of the component:之后,我在组件的返回中显示查看器和位置值:

return (
 <Grid container>
  <Grid item xs={9}>
   <div id="viewer"/>
  </Grid>
  <Grid item container xs={3}>
    <Typography>
     X: {locations[0]}
     Y: {locations[1]}
     Z: {locations[2]}
    </Typography>
  </Grid>
</Grid>

); );

In each change of locations values, the page is re-rendered and the also the viewer re-renders, I need a way to not re-render the viewer (the creation of the viewer is in useEffect) and just update the useState values (locations)在位置值的每次更改中,页面都会重新呈现,查看器也会重新呈现,我需要一种方法来不重新呈现查看器(查看器的创建在 useEffect 中)并且只更新 useState 值(地点)

PS: I shrinked code to be more comprehensible PS:我缩小了代码以便更容易理解

If you pass an empty array as the second parameter in useEffect the viewer will render when mounted the first time.如果您在 useEffect 中传递一个空数组作为第二个参数,则查看器将在第一次安装时呈现。 By leaving out the dependancy array it will re-render every time.通过省略依赖数组,它每次都会重新渲染。 For more information on the React useEffect Hook: https://reactjs.org/docs/hooks-effect.html有关 React useEffect Hook 的更多信息: https://reactjs.org/docs/hooks-effect.html

useEffect(()=>{
    const container = document.getElementById('viewer');
    var child = container.lastElementChild; 
    if (child) document.getElementById('viewer').removeChild(child); 
    // deleting the viewer if it exists
    const element = document.createElement('div');
    Viewer.setContainer(element);
    Viewer.onUpdate(locations => {
      setLocations(locations);
      });
    }, [])

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM