繁体   English   中英

父级重新渲染是否会触发其自定义挂钩以“重新创建”?

[英]Does a parent rerender trigger its custom hook to be "re-created"?

我正在尝试对自定义挂钩有一个基本的了解。 我目前有一个parent组件和一个自定义钩子来处理它的一些逻辑。 我的自定义钩子看起来像:

export const useTrip = () => {
    const origin = useSelector((store) =>
        store.trip.origin
    )
    const destination = useSelector((store) =>
        store.trip.destination
    )
    const [waypoints, setWaypoints] = useState([])
    const [value, setValue] = useState(null)

    useEffect(() => {
        expensiveFunction()
    }, [origin, destination])
    const getMidpoints = (value) => {
       ...
       setWaypoints(result)
    }
    console.log("this triggers way more times than expected")
    const expensiveFunction = () => {
       ...
       setValue(result)
    }
    return { getMidpoints, waypoints, value }
}

我的自定义钩子中有很多东西,但似乎我的自定义钩子“重新渲染”了太多次,正如我在console.log中看到的那样,这个自定义钩子被重新渲染是有原因的吗?

编辑:经过更多测试,似乎如果我的useEffect钩子的依赖项发生变化,则重新运行整个自定义钩子,并且我再次看到我的console.log行。 这是自定义钩子的正确行为吗? 还是我使用不正确

您应该考虑始终运行自定义挂钩的 function,或者只要 react 喜欢运行它

只有传递给钩子内部useEffect调用的函数可能会被较少调用(即,如果它们的依赖关系发生变化)

所以,是的,你在钩子里的console.log被调用这么多次是可以的(假设主function被调用这么多次是正确的)

一心 model

你可以把它想象成一个心理模型,就像你的自定义钩子的全部内容都在你的主 function 中,例如:

const useMyHook = () => {
    console.log('this line was ivoked');
    useEffect(()=>{
        console.log('useEffect was ivoked');
    });
};

const Main = ( props ) => {
    useMyHook();
    return <>nothing</>
};

行为与以下内容几乎相同:

const Main = ( props ) => {
    
    console.log('this line was ivoked');
    useEffect(()=>{
        console.log('useEffect was ivoked');
    });
    
    return <>nothing</>
};

如何理解挂钩调用

您不应该依赖钩子函数本身运行的时间和频率,而应该只依赖 react 为您提供的保证,例如:

  • 如果...,则某些 state 保证是最新的,或者
  • 如果...,将调用此 useEffect function
  • ...

较小的挂钩

你说“我的自定义钩子里还有很多东西……” 我建议将您的自定义挂钩分解为较小的自定义挂钩。

暂无
暂无

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

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