简体   繁体   English

为什么即使 StaticComponent 没有更改 state 也会重新渲染?

[英]Why does StaticComponent re-render even though it has no changing state?

I'm trying to understand the fundamentals of how React re-renders components on state change.我试图了解 React 如何在 state 更改上重新呈现组件的基础知识。

In the example below, the console.log('hi') statement in StaticComponent runs each time I trigger the onChange handler on the input element.在下面的示例中,每次我触发输入元素上的onChange处理程序时, StaticComponent中的console.log('hi')语句都会运行。 I'm confused about why StaticComponent re-renders each time I update state. It doesn't get any props related to the changing state, so why does the log statement run each time?我很困惑为什么每次更新 state 时StaticComponent都会重新渲染。它没有获得与更改 state 相关的任何道具,那么为什么日志语句每次都运行? React dev tools also shows the component re-rendering each change with the "highlight" feature. React 开发工具还显示组件使用“突出显示”功能重新呈现每个更改。

Is this normal react behavior?这是正常的反应行为吗? Feels like it violates most of what I've read about react so far, and it being economical by only updating what needs to be.感觉它违反了我到目前为止读到的关于 React 的大部分内容,而且它通过只更新需要的内容来经济。

import { useState } from 'react';

const DisplayComponent = ({ text }) => {
  return <p>{text}</p>
}

const StaticComponent = () => {
  console.log('hi')
  return <p>text</p>
}

export default function Home() {
  const [displayText, setDisplayText] = useState()
  return (
    <>
      <DisplayComponent text={displayText} />
      <StaticComponent />
      <input onChange={(event) => setDisplayText(() => event.target.value)} type="text" value={displayText}/>
    </>
  );
}

Unfortunately, it's a normal react behavior.不幸的是,这是一种正常的反应行为。 However, it would just rerender the virtual DOM but not the actual DOM.但是,它只会重新渲染虚拟 DOM 而不是实际的 DOM。

If you still want to prevent that.如果你仍然想阻止它。 The memo is what you need. memo正是您所需要的。

import { useState, memo } from 'react';

const DisplayComponent = ({ text }) => {
  return <p>{text}</p>
}

const StaticComponent = memo(() => {
  console.log('hi')
  return <p>text</p>
})

export default function Home() {
  const [displayText, setDisplayText] = useState()
  return (
    <>
      <DisplayComponent text={displayText} />
      <StaticComponent />
      <input onChange={(event) => setDisplayText(() => event.target.value)} type="text" value={displayText}/>
    </>
  );
}

For more infomation https://beta.reactjs.org/reference/react/memo有关更多信息,请访问 https://beta.reactjs.org/reference/react/memo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM