reactjs - React hook 依赖函数作为 props
问题描述
在阅读了 hooks 的介绍之后,我立即感觉到它在传递函数道具方面存在性能问题。
考虑以下类组件,其中函数引用是一个绑定函数,因此不会发生重新渲染。
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
推荐阅读
- python - 返回包含一些文本的行并删除其余行
- python - 尝试在 PHP 中运行 Python 脚本时出现 Exec 格式错误。为什么?
- pytorch - 如何修复缩放优化 pytorch 代码错误
- reactjs - 如何在 React with Typescript 中使用 Immutable.js 对象列表?
- robotframework - Robot Framework:在相同的测试用例中测试两台服务器
- ios - Login with token authentication SWIFT
- java - 使用java PDFBox从未选择的PDF内容中提取文本
- typescript - 在 TypeScript 中获取递归属性的联合类型
- python - 如何比较多个列表的每个元素并返回不同的列表名称
- javascript - 如何将 JSON 对象键值对传递到 HTML href 标记?