React hook 依赖函数作为 props
React hook dependent functions as props
通读了 hooks 的介绍后,我立即感觉到它在传递函数 props 时存在性能问题。
考虑以下 class 组件,其中函数引用是绑定函数,因此不会因此发生重新渲染。
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>
);
}
}
现在将其与钩子版本进行比较,在钩子版本中,我们将每次渲染时的新函数传递给按钮。如果 <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
通读了 hooks 的介绍后,我立即感觉到它在传递函数 props 时存在性能问题。
考虑以下 class 组件,其中函数引用是绑定函数,因此不会因此发生重新渲染。
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>
);
}
}
现在将其与钩子版本进行比较,在钩子版本中,我们将每次渲染时的新函数传递给按钮。如果 <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