【问题标题】:named function and arrow function in event handler in react反应中事件处理程序中的命名函数和箭头函数
【发布时间】:2023-01-27 09:12:47
【问题描述】:

下面的代码有什么问题?

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <h2>{count}</h2>
      <button
        onClick={() => {
          setCount((count) => count + 1);
        }}
      >
        increase
      </button>
    </div>
  );
}

在事件处理程序中使用箭头函数会导致重新渲染并影响性能吗?

有人争辩说我应该这样做。

const [count, setCount] = useState(0);
  const increment = () => setCount((count) => count + 1);

  return (
    <div className="App">
      <h2>{count}</h2>
      <button onClick={increment}>increase</button>
    </div>
  );

对我来说,这只是一个偏好问题,它不会提高性能,对吗?

https://codesandbox.io/s/purple-breeze-8xuxnp?file=/src/App.js:393-618

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    当状态更改、父(或子)重新呈现、上下文更改和挂钩更改时,React 会触发重新呈现。因此,在上面的示例中,无论是提取函数还是只是在 html 中简单地键入函数,重新呈现都没有区别。

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 2019-05-13
      • 2022-11-14
      • 2021-10-23
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多