【问题标题】:React Hooks: how to avoid re-rendering of component on another state change?React Hooks:如何避免在另一个状态更改时重新渲染组件?
【发布时间】:2021-08-24 10:19:38
【问题描述】:

这是我的代码。

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”区域中的&lt;button&gt; 时重新渲染“#buttons”区域和“#content”区域。

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

【问题讨论】:

  • 这是一个重复的问题,请看this
  • 您为什么担心title 重新渲染?
  • @Joshua 我想知道是否可以优化组件的渲染。
  • 您无需担心微优化。尤其是在这样的事情上。

标签: reactjs react-hooks use-state


【解决方案1】:

使用不同的组件和 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>
    </>
)
}

来自文档:

如果你的组件在给定相同的 props 的情况下呈现相同的结果,你 可以将其包装在对 React.memo 的调用中,以提高某些性能 通过记忆结果来处理案例。

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

【讨论】:

    【解决方案2】:

    您应该将"#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 />
    

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 2020-06-26
      • 2022-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多