渲染带钩子和不带钩子的功能组件有什么区别吗?

Is there any difference between rendering a functional component with and without hooks?

刚刚尝试了一些 react-hooks 并遇到了一些问题。

考虑这个带有 react-hooks 的功能组件:

const Counter = (props) => {
  console.log("Counter component");

  const [count, setCount] = useState(0);

  const handleIncrease = () => {
    setCount(count + 1);
  }

  const handleDecrease = () => {
    setCount(count - 1);
  }

  return (
    <div>
      <button onClick={handleIncrease}>+</button>
      <button onClick={handleDecrease}>-</button>
      <p>{count}</p>
    </div>
  )
}

每次我点击“+”或“-”时它都会记录。

这是否意味着这个组件(或者函数)中的每个处理程序都被重新声明并重新分配给一个变量?如果是这样,会不会导致一些性能问题?

对我来说,带钩子的函数式组件看起来像是像这样的经典组件的巨大渲染方法:

class Counter extends React.Component {
  state = {
    count: 0,
  }

  render() {
    const handleIncrease = () => {
      this.setState({ count: this.state.count + 1 });
    }

    const handleDecrease = () => {
      this.setState({ count: this.state.count - 1 });
    }

    return (
      <div>
        <button onClick={handleIncrease}>+</button>
        <button onClick={handleDecrease}>-</button>
        <p>{count}</p>
      </div>
    )
  }
}

我认为没有人会这样做。

我是否对 React 的渲染机制有误解,或者这不是将功能组件与 react-hooks 一起使用时的最佳实践?

尽管在功能组件中,功能在每次渲染时都会重新创建,但与收益相比,它的性能成本要低得多。

您可以参考这个post了解更多详情:

但是您仍然可以进行优化,这样函数就不会在使用 useCallbackuseReducer(depending on whether your updates are complex or not)

的每个渲染器上重新创建
const Counter = (props) => {
  console.log("Counter component");

  const [count, setCount] = useState(0);

  const handleIncrease = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, [])

  const handleDecrease = useCallback(() => {
    setCount(prevCount => prevCount + 1);
  }, [])

  return (
    <div>
      <button onClick={handleIncrease}>+</button>
      <button onClick={handleDecrease}>-</button>
      <p>{count}</p>
    </div>
  )
}

在上面的示例中,函数仅在初始渲染时重新创建,使用状态更新回调我们可以更新状态并避免关闭问题