React Hooks:如何避免在另一个状态更改时重新渲染组件?

React Hooks: how to avoid re-rendering of component on another state change?

这是我的代码。

const test = () => {
    const [state, setState] = useState(0)
    const clickOne = () => setState(1)
    const clickTwo = () => setState(2)

    return (
        <>
        <div className="title">
            <h1>Title</h1>
        </div>
        <div className="buttons">
            <button onClick={clickOne}>1</button>
            <button onClick={clickTwo}>2</button>
        </div>
        <div className="content">
            {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
        </div>
        </>
    )
}

我在这里尝试的是在“#buttons”区域<button>时重新渲染“#buttons”区域和“#content”区域被点击。

截至目前,每次单击按钮时都会重新呈现“#title”区域。 如何强制不重新渲染“#title”区域?谢谢。

您应该将 "#title 拆分成一个组件。

const Title = () => {
  return (
    <div className="title">
      <h1>Title</h1>
    </div>
  );
};

const Test = () => {
  const [state, setState] = useState(0);
  const clickOne = () => setState(1);
  const clickTwo = () => setState(2);

  return (
    <>
      <div className="buttons">
        <button onClick={clickOne}>1</button>
        <button onClick={clickTwo}>2</button>
      </div>
      <div className="content">
        {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
      </div>
    </>
  );
};

并在父组件中使用

<Title />
<Test />

使用不同的组件和React.memo

const Header = React.memo(() => {
  return (<div className="title">
        <h1>Title</h1>
    </div>)
});

const test = () => {
const [state, setState] = useState(0)
const clickOne = () => setState(1)
const clickTwo = () => setState(2)

return (
    <>
    <Header/>
    <div className="buttons">
        <button onClick={clickOne}>1</button>
        <button onClick={clickTwo}>2</button>
    </div>
    <div className="content">
        {state === 0 ? <div>click!</div> : state === 1 ? <div>1</div> : <div> 2 </div>}
    </div>
    </>
)
}

来自文档:

If your component renders the same result given the same props, you can wrap it in a call to React.memo for a performance boost in some cases by memoizing the result.

但请注意,您不能使用它来依赖渲染预防,而只是优化