反应依赖于钩子的函数作为道具

时间:2019-03-14 18:20:59

标签: reactjs react-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>
    );
  }
}

现在将其与hooks-version进行比较,在hooks-version中,我们在每个渲染器上将新函数传递给按钮。如果呈现<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>
  );
}

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

我该如何避免重新渲染依赖于挂钩的带有功能道具的所有东西?

1 个答案:

答案 0 :(得分:3)

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

相关问题