这是我的代码。
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>
</>
)
}
我在这里尝试的是仅在 <button>
时重新渲染“#buttons”区域和“#content”区域单击“#buttons”区域。
到目前为止,每次单击按钮时都会重新渲染“#title”区域。 如何强制“#title”区域不重新渲染?谢谢。
最佳答案
使用不同的组件和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.
但请注意,您不能使用它来依赖渲染预防,而只是优化
关于reactjs - react Hook : how to avoid re-rendering of component on another state change?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68905784/