[英]React hook dependent functions as props
通過對鈎子的介紹閱讀后,我立即感覺到它在傳遞函數道具時存在性能問題。
考慮以下類組件,其中函數引用是綁定函數,因此不會發生重新渲染。
import React from 'react';
class Example extends React.Component {
state = { count: 0 }
onIncrementClicked = () => setState({ count: this.state.count + 1 })
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.onIncrementClicked}>
Click me
</button>
</div>
);
}
}
現在將它與hooks-version進行比較,我們將每個渲染的新函數傳遞給按鈕。 如果<Example />
組件呈現,則無法避免重新呈現它的<button />
子元素。
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
我知道這是一個小例子,但考慮一個更大的應用程序,其中許多回調傳遞依賴於鈎子。 怎么可以這個優化?
我如何避免重新渲染所有需要函數道具的東西,這取決於鈎子?
您可以使用useCallback確保事件處理程序在具有相同count
數值的呈現之間不會更改:
const handleClick = useCallback(
() => {
setCount(count + 1)
},
[count],
);
為了更好地優化,您可以將count
數值存儲為按鈕的屬性,這樣您就不需要在事件處理程序中訪問此變量:
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const handleClick = useCallback(
(e) => setCount(parseInt(e.target.getAttribute('data-count')) + 1),
[]
);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick} data-count={count}>
Click me
</button>
</div>
);
}
另請查看https://reactjs.org/docs/hooks-faq.html#are-hooks-slow-because-of-creating-functions-in-render
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.