你能解释一下为什么 handleClick 函数总是新的吗?
function Foo() {
const handleClick = () => {
console.log('Click happened');
}
return <Button onClick={handleClick}>Click Me</Button>;
}
最佳答案
请记住,Foo()
也是一个在每次渲染时重新运行的 JavaScript 函数。
在该函数内部有一个语句是:
const handleClick = () => {...};
含义:创建一个函数并将其赋值给我最近创建的局部变量handleClick
。因此,它将在每次渲染时重新创建。
这对性能的影响通常接近于零。但如果需要,您可以为此进行优化。
const handleClick = useCallback(()=>{...},[dependencyArray]);
如果该函数依赖于可能发生变化的变量,您可以将它们添加到 dependencyArray
中,如果其中一个发生变化,React 将重新创建该函数。否则它将保留上次创建时的相同功能。
Are Hooks slow because of creating functions in render?
No. In modern browsers, the raw performance of closures compared to classes doesn’t differ significantly except in extreme scenarios.
发件人:https://reactjs.org/docs/hooks-reference.html#usecallback
useCallback()
Returns a memoized callback.
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders (e.g. shouldComponentUpdate).
关于javascript - 为什么箭头函数在渲染之间没有被内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56476880/