gpt4 book ai didi

reactjs - useEffect hook - 依赖项 - 重新渲染问题

转载 作者:行者123 更新时间:2023-12-03 16:32:47 32 4
gpt4 key购买 nike

第一种情况:
_假设我有一个处于 redux 状态或 parent 状态的 Prop 。
_我不希望 useEffect 在此 Prop 更改时触发,
_但我确实需要使用 useEffect 中的 Prop 。
_React 警告我将 prop 添加到依赖数组中,但如果我这样做了,那么 useEffect 将再次触发。
第二种情况:
_我在 useEffect 中使用一个函数,
_但是其他地方也需要这个功能。
_不想重复功能代码。
_React 希望我将函数添加到依赖数组中,但我不希望每次函数引用更改时都会触发 useEffect。

最佳答案

在使用 useEffect 时,您应该考虑闭包。如果在 useEffect 中使用了任何 props 或局部变量,则建议将其包含在依赖数组中,否则由于关闭,您将使用过时的数据。
这里我介绍一个用例。在 ComponentUsingRef 中,我们使用 ref 作为容器。您可以在 https://reactjs.org/docs/hooks-reference.html#useref 找到更多相关信息

Advantage of this approach is that you wont be bound to memoize fn inyour parent component. You will always be using latest value offunction and in the given case it won't even cause firing of useEffect as it won't be on your dependency


const Component=({fn})=>{
useEffect(()=>{
fn()
},[fn])
.....
.....
return <SomeComponent {...newProps}/>
}

const ComponentUsingRef=({fn}){
const fnRef = useRef(fn)
fnRef.current = fn // so that our ref container contains the latest value
useEffect(()=>{
fn.current()
},[ ])
.....
.....
return <SomeComponent {...newProps}/>
}
如果你想使用抽象,那么你应该在 custom hook 中提取你的逻辑。

关于reactjs - useEffect hook - 依赖项 - 重新渲染问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63731065/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com