在自定义挂钩和组件中使用 useEffect 有什么区别
what is the difference between using useEffect inside a custom hook and a component
我想知道在组件中使用 useEffect
挂钩和自定义挂钩的区别 b/w。
例如
如果我有一个功能组件(Component),直接在里面使用useEffect
hook
import React,{useEffect} from 'react';
function Component(){
useEffect(()=>{
//some code //callback fires after component renders
},)
return (<div>Component</div>)
}
如果创建自定义挂钩 (useCustomHook)
import React,{useEffect} from 'react';
function useCustomHook(){
useEffect(()=>{
//some code //this callback also get fired after component renders
})
}
现在如果我在组件中使用这个自定义钩子
import useCustomHook from 'customhook';
import React,{useEffect} from 'react';
function Component(){
useCustomHook();
return(<div>Component</div>)
}
我想知道
useEffect
钩子是否与Component
有关,所以它只在Component
渲染后回调运行,因为在使用useCustomHook
它在 Component
之外声明,即它在自定义挂钩内,但是回调 get 也仅在 Component
呈现后被调用,
那么b/wuseEffect
和Component
有关系吗,所以useEffect
get的回调只有在Component
渲染后才会调用,不管useEffect
是在 Component
内部还是外部声明的,即 (useCustomHook)
除非调用自定义挂钩,否则不会评估其中的逻辑,因此无论您在其中定义什么挂钩,它们在定义时都不是 运行
自定义挂钩中的 useEffect
函数仅当您在功能组件中使用它并调用它时才会 运行。另请注意,useEffect
的行为将与在功能组件本身内部编写的行为完全相同
假设你在功能组件里面写了3个效果。您还有 2 个自定义挂钩,每个挂钩有 1 个效果。所以当你在你的功能组件中使用这些自定义钩子时,你可以想象现在你的功能组件中总共有 5 个效果,当组件被渲染后满足条件时,它们的回调函数将被调用。
功能组件内定义的效果 运行s 在呈现组件和绘制浏览器之后。 React 还保证所有效果都将在下一次渲染之前 运行。但是 effect 回调函数的调用顺序完全取决于执行它所花费的时间。
这是解释我的观点的代码沙盒的 link
https://codesandbox.io/s/adoring-murdock-5ifil?file=/src/useTry.js
我想知道在组件中使用 useEffect
挂钩和自定义挂钩的区别 b/w。
例如
如果我有一个功能组件(Component),直接在里面使用useEffect
hook
import React,{useEffect} from 'react';
function Component(){
useEffect(()=>{
//some code //callback fires after component renders
},)
return (<div>Component</div>)
}
如果创建自定义挂钩 (useCustomHook)
import React,{useEffect} from 'react';
function useCustomHook(){
useEffect(()=>{
//some code //this callback also get fired after component renders
})
}
现在如果我在组件中使用这个自定义钩子
import useCustomHook from 'customhook';
import React,{useEffect} from 'react';
function Component(){
useCustomHook();
return(<div>Component</div>)
}
我想知道
useEffect
钩子是否与Component
有关,所以它只在Component
渲染后回调运行,因为在使用useCustomHook
它在 Component
之外声明,即它在自定义挂钩内,但是回调 get 也仅在 Component
呈现后被调用,
那么b/wuseEffect
和Component
有关系吗,所以useEffect
get的回调只有在Component
渲染后才会调用,不管useEffect
是在 Component
内部还是外部声明的,即 (useCustomHook)
除非调用自定义挂钩,否则不会评估其中的逻辑,因此无论您在其中定义什么挂钩,它们在定义时都不是 运行
自定义挂钩中的 useEffect
函数仅当您在功能组件中使用它并调用它时才会 运行。另请注意,useEffect
的行为将与在功能组件本身内部编写的行为完全相同
假设你在功能组件里面写了3个效果。您还有 2 个自定义挂钩,每个挂钩有 1 个效果。所以当你在你的功能组件中使用这些自定义钩子时,你可以想象现在你的功能组件中总共有 5 个效果,当组件被渲染后满足条件时,它们的回调函数将被调用。
功能组件内定义的效果 运行s 在呈现组件和绘制浏览器之后。 React 还保证所有效果都将在下一次渲染之前 运行。但是 effect 回调函数的调用顺序完全取决于执行它所花费的时间。
这是解释我的观点的代码沙盒的 link https://codesandbox.io/s/adoring-murdock-5ifil?file=/src/useTry.js