首页 > 解决方案 > 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>
  );
}

我知道这是一个小例子,但考虑一个更大的应用程序,其中传递了许多依赖于钩子的回调。如何优化?

我如何避免重新渲染所有需要函数道具的东西,这取决于钩子?

标签: reactjsreact-hooks

解决方案


您可以使用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


推荐阅读