我正在尝试深入理解useEffect钩子。
我想知道什么时候使用哪种方法,为什么?
1.useEffect with no second paraments
useEffect(()=>{})
2.useEffect with second paraments as []
useEffect(()=>{},[])
3.useEffect with some arguments passed in the second parameter
useEffect(()=>{},[arg])发布于 2020-01-21 21:10:41
useEffect(callback);
// Example
useEffect(() => {
console.log("executed after render phase");
return () => {
console.log("cleanup function after render");
};
});const Component = () => {
callback()
return <></>;
};注释:在执行时间上仍然存在差异(参见下一个注释)。Check this sandbox logs。
useEffect(callback,[]);
// Example
useEffect(() => {
const fetchUsers = async () => {
const users = await fetch();
setUsers(users);
};
fetchUsers();
console.log("called on component's mount");
return () => {
console.log("called on component's unmount");
};
}, []);Gotchas:
后执行的回调
请记住,有一个先渲染和,然后挂载。
由于closures导致的
粗略地说,关于
useEffect的大多数bug都是不知道闭包是如何工作的,也没有注意到linting警告。确保数组包含组件作用域中随时间变化并由效果使用的所有值。否则,您的代码将引用先前呈现的陈旧的值- note in React docs。
useEffect(callback,[arg]);
// Example
useEffect(() => {
console.log({ users });
return () => {
console.log("user value is changing");
};
}, [users]);可以提供用于在属性/状态上运行事件的value.
[arg1,arg2,arg3...]arg
arg 注意事项:
arg.的
即比较上一次渲染的
arg和当前渲染的prevArg === arg ? doNothing() : callback()的值。
{} === {} || [] === []是一个falsy语句,如果arg (在我们的示例中是users)是一个对象,则回调将在每次呈现时运行。其他需要了解的要点
useEffect回调fired after browser's re-paint.useEffect回调在声明顺序函数(,like all hooks)中执行的回调,请检查cleanup useEffect是否应包含使用useRef中的值的cleanup,在cleanup函数中,将该值复制到回调的作用域const timeoutIdRef = useRef();
useEffect(() => {
const timeoutId = timeoutIdRef.current;
return () => {
/*
Using timeoutIdRef.current directly here is not safe
since you can't guarantee the ref to exists in this point
(especially when the component unmounts)
*/
// Should get a lint warning here
clearTimeout(timeoutIdRef.current); // BAD
// Closure on timeoutId value
clearTimeout(timeoutId); // GOOD
};
}, [arg]);ref.current as useEffect's dependency when ref points to a DOM element?useEffect ,those are the common patterns.const isMounted = useRef(false);
useEffect(() => {
if (isMounted.current) {
// first mount
} else {
isMounted.current = true;
}
}, [arg]);继续阅读:
return语句useEffect callbackuseEffect by Dan AbramovuseEffect API发布于 2020-01-21 21:16:29
如果您熟悉React类生命周期方法,则可以将useEffect挂钩看作componentDidMount、componentDidUpdate和componentWillUnmount的组合。
1.不带第二个参数的used :当我们想要发生某些事情时,无论是在组件刚刚挂载时,还是在组件已经更新时,都可以使用它。从概念上讲,我们希望它在每次渲染之后发生。
2.使用executes,第二个参数为[]:当我们希望在组件挂载时发生某些事情时,如果只在mounting.It时执行一次,则使用executes,因为它更接近熟悉的componentDidMount和componentWillUnmount。
3.在第二个参数中传递一些参数时使用eg :这是当我们希望在pramter传递时发生某些事情时使用,例如。在您的情况下,参数发生了变化。
了解更多信息。点击这里:https://reactjs.org/docs/hooks-effect.html
https://stackoverflow.com/questions/59841800
复制相似问题