渲染带有或不带有挂钩的功能组件之间有什么区别吗?

时间:2019-04-04 23:18:29

标签: reactjs 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一起使用时,这不是最佳实践吗?

1 个答案:

答案 0 :(得分:1)

尽管在功能组件中,每个渲染都会重新创建功能,但是与性能相比,其性能成本要低得多。

您可以参阅此帖子以获取更多详细信息:Performance penalty of creating handlers on every render

不过,您仍然可以进行优化,以免在使用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>
  )
}

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