【问题标题】:React hook dependent functions as propsReact hook 依赖函数作为 props
【发布时间】: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>
    );
  }
}

现在将它与钩子版本进行比较,我们在每次渲染时将新函数传递给按钮。如果 &lt;Example /&gt; 组件渲染,则无法避免重新渲染它的 &lt;button /&gt; 子组件。

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


【解决方案1】:

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

【讨论】:

  • setCount(c =&gt; c + 1) 也适用于这种情况,不依赖于count
猜你喜欢
  • 2020-12-29
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多