简体   繁体   English

反应功能组件中使用和不使用useEffect的区别

[英]Difference between with and without useEffect in react functional component

I have a react functional component and I want to run some code in every render.我有一个反应功能组件,我想在每次渲染中运行一些代码。 You know useEffect hook without dependency array runs every time on render.您知道每次渲染时都会运行没有依赖数组的useEffect钩子。

heres the code这是代码

function Component({a, b}){

useEffect(()=>{
  console.log('component rerenderd')
  // some code here
})

 return(
  <div>
    Some content
  </div>
  )
}

on the other hand without useEffect doing same thing另一方面,没有 useEffect 做同样的事情

function Component2({a, b}){

  console.log('component rerenderd')
  // some code here

 return(
  <div>
    Some content
  </div>
  )
}

My question is what is the difference between both of them?我的问题是它们两者之间有什么区别?

useEffect callbacks executed after the render phase which is the main difference between the two. 在渲染阶段之后执行的useEffect回调,这是两者之间的主要区别。

See the next example:请参见下一个示例:

// Log order:
// "executed at render phase"
// "executed after render phase"

const App = () => {
  useEffect(() => {
    console.log("executed after render phase");
  });

  console.log("executed at render phase");

  return <></>;
};

编辑 useEffect 执行阶段

In the second case, you're logging before returning the JSX.在第二种情况下,您在返回 JSX 之前进行日志记录。 When you're using the first snippet the code inside the callback passed to useEffect runs after the component renders.当您使用第一个片段时,传递给useEffect的回调中的代码会在组件呈现后运行。

There are multiple other uses for using useEffect like doing something when the state changes etc.使用useEffect还有多种其他用途,例如在 state 发生变化时做某事等。

在此处输入图像描述

Functional components' entire function body is basically the "render" function, so anything there is called each time the component is rendered, which occurs during the "Render phase" which can be paused, aborted, or restarted by React when it is computing a diff.功能组件的整个 function 主体基本上是“渲染” function,因此每次渲染组件时都会调用其中的任何内容,这发生在“渲染阶段”,可以在 React 计算时暂停、中止或重新启动差异。

The useEffect hook's callback is guaranteed to be called only once per render cycle, ie it is more akin to the componentDidMount , componentDidUpdate , and componentWillUnmount lifecycle functions. useEffect挂钩的回调保证在每个渲染周期只被调用一次,即它更类似于componentDidMountcomponentDidUpdatecomponentWillUnmount生命周期函数。 Take note that these occur in the "Commit phase", meaning the DOM had been diffed and react is committing/flushing the UI changes to the DOM.请注意,这些发生在“提交阶段”,这意味着 DOM 已经被区分并且反应正在提交/刷新对 DOM 的 UI 更改。

Try rendering your component with react's strict mode on and you'll definitely see a difference.尝试使用 react 的严格模式渲染你的组件,你肯定会看到不同。

Detecting unexpected side effects 检测意外的副作用

useEffect can take 2 arguments, the first is a function and the second one is an array. useEffect 可以取 2 个 arguments,第一个是 function,第二个是数组。

the function is being called as soon as the component gets mounted, but the extended feature that useEffect has is that it has a kind of sensivity list, which lets it run again in case of any argument in the second array changes. function 一旦组件被安装就会被调用,但是 useEffect 的扩展特性是它有一个敏感列表,如果第二个数组中的任何参数发生变化,它可以再次运行。 making it componentDidUpdate too.也使它成为 componentDidUpdate 。

but the console.log() without useEffect runs the way it runs.但是没有 useEffect 的 console.log() 会按照它的运行方式运行。 you don't have any control to it.你无法控制它。 this is a simple example:这是一个简单的例子:

useEffect(() => {
  console.log('count=', count);
}, [count]); // Only re-run the effect if count changes

It also has a cleanUp method, you can (for instance) write a time interval and it could be cleared when the component get unmounted.它还有一个 cleanUp 方法,你可以(例如)写一个时间间隔,当组件被卸载时它可以被清除。 you can add a function named 'return' in the useEffect and it's done!您可以在 useEffect 中添加一个名为“return”的 function 并完成!

let timer;

useEffect(()=>{
  timer = setInterval(() => console.log('hello!'), 1000);
  return()=>clearImmediate(timer);
})

Now the interval gets cleared when the component gets unmounted.现在,当组件卸载时,间隔会被清除。

Now if we pass something in the array to make useEffect listen to their change, the component will do the cleanUp method when useEffect runs again with the new value.现在如果我们在数组中传递一些东西让 useEffect 监听它们的变化,当 useEffect 再次使用新值运行时,组件将执行 cleanUp 方法。

this is an example:这是一个例子:

let timer;

useEffect(()=>{
  timer = setInterval(() => console.log('do you need something Mr./Mrs. ' + someOne + ' ?'), 1000);
  return()=>clearImmediate(timer);
},[someOne]);

We made a timer which asks someOne if he/she needs something every second.我们制作了一个计时器,每秒询问某人是否需要某些东西。 Now if the 'someOne' changes, it stops asking the previous one and starts to ask the new 'someOne' every second.现在,如果“someOne”发生变化,它会停止询问前一个并开始每秒询问新的“someOne”。

by the way, you can name the function 'return' anything you want, or you can just pass an arrow function.顺便说一句,您可以将 function 命名为“返回”任何您想要的东西,或者您可以只传递一个箭头 function。

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

相关问题 function 和功能性 React 组件有什么区别? - What is the difference between function and functional React component? 在反应功能组件中使用 useEffect 时出错 - Error using useEffect in react functional component 输入验证与功能组件和 useEffect 挂钩 - Input validation in react with functional component and useEffect hook 切换到功能组件的问题与 useEffect 反应 - Problem switching to functional component react with useEffect 常规 JavaScript 函数与 React 函数式组件的区别 - Difference between Regular JavaScript functions and React Functional Component usePreviousDistinct 和 useEffect 之间的区别 - Difference between usePreviousDistinct with useEffect and without React Native - Class 组件到功能组件(UseEffect:state 未定义) - React Native - Class Component to Functional Component (UseEffect: state undefined) React class 组件和 React 功能组件之间的 redux 存储更改后访问道具的差异 - Difference in accessing props after change in redux store between React class component and React functional component 使用 useState 重新渲染功能性 React 组件并确保执行 useEffect 钩子 - Rerender a functional React component using useState and ensure useEffect hook executed 我是否无法在功能性 React 组件中使用带有 useEffect 的内联“if”? - Am I unable to use inline “if” with useEffect in a functional React component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM