React Hooks 和 jsx-no-lambda 警告

React Hooks and jsx-no-lambda warning

所以现在除了禁用警告之外我们不能将钩子用作事件函数的旧样式什么是调用不违反规则的事件函数的最佳方法

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)}> // Lambdas are forbidden in JSX attributes due to their rendering performance impact (jsx-no-lambda)
        Click me
      </button>
    </div>
  );
}

有了钩子,创建内联箭头函数的性能损失相对于 class 组件的好处可以忽略不计,因此您不必担心渲染中的箭头函数。

您可以禁用此 eslint 规则。

然而,您仍然通过编写 increment 方法并使用 useCallback 钩子将其记忆化来改进您的代码。这在您尝试将处理程序传递给嵌套组件时特别有用,然后您可以使用 React.memo

优化重新渲染

const Button = React.memo(function Btn({increment}) {
    return (
       <button onClick={increment}>
          Click me
      </button>
    )
})
function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = React.useState(0);
  const increment = React.useCallback(() => {
      setCount(prev => prev+1);
  }, [])
  return (
    <div>
      <p>You clicked {count} times</p>
      <Button increment={increment}/>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>