【发布时间】:2019-08-05 18:18:28
【问题描述】:
在阅读了 hooks 的介绍后,我立即感觉到它在传递函数 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>
);
}
}
现在将它与钩子版本进行比较,我们在每次渲染时将新函数传递给按钮。如果 <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>
);
}
我知道这是一个小例子,但考虑一个更大的应用程序,其中传递了许多依赖于钩子的回调。如何优化?
如何避免重新渲染所有需要函数道具的东西,这取决于钩子?
【问题讨论】:
-
常见问题解答中特别提到了这一点,并表示这不应该是一个问题:reactjs.org/docs/…
标签: reactjs react-hooks