gpt4 book ai didi

javascript - 性能 - 功能组件中的功能

转载 作者:行者123 更新时间:2023-11-30 11:00:41 25 4
gpt4 key购买 nike

当功能组件具有内部功能时,我对性能有一些疑问。

当拥有一个带有内部函数的功能组件时,是否会在每次渲染时一遍又一遍地重新创建该内部函数?在那种情况下,如果我要使用 React.memo() 来内存组件,那么该函数也会被内存吗?

这是我所指的一个虚拟示例:

const MyComponent = React.memo(({genre, name}) => {
const someFunction = genre => {
return (genre === 'male') ? 'Mr.' : 'Ms.';
}

return (
<h1>Hello {someFunction(genre)} {name}!</h1>
);
});

最佳答案

来自 React Hooks 文档:

Are Hooks slow because of creating functions in render?

No. In modernbrowsers, the raw performance of closures compared to classes doesn’tdiffer significantly except in extreme scenarios.[...]

Traditionally, performance concerns around inline functions in Reacthave been related to how passing new callbacks on each render breaksshouldComponentUpdate optimizations in child components. Hooksapproach this problem from three sides.

  • The useCallback Hook lets you keep the same callback reference betweenre-renders so that shouldComponentUpdate continues to work:

  • The useMemo Hook makes it easier to control when individual childrenupdate, reducing the need for pure components.

  • Finally, the useReducer Hook reduces the need to pass callbacksdeeply, as explained below.

阅读更多 here .

同样在您的示例中,您可以将内部函数放在函数组件之外,因为它不使用组件内部的任何东西,如下所示:

const someFunction = genre => {
return (genre === 'male') ? 'Mr.' : 'Ms.';
}

const MyComponent = React.memo(({genre, name}) => {
return (
<h1>Hello {someFunction(genre)} {name}!</h1>
);
});

关于javascript - 性能 - 功能组件中的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875655/

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