簡體   English   中英

將重新呈現限制為功能組件的特定狀態更改

[英]Restricting re-renders to specific state change in functional component

如果我有一個具有三種不同狀態的組件,並且只希望當該組件中的一個特定狀態發生更改時重新渲染該組件,我該怎么做呢?

下面,我提供了一個代碼示例。 說我只希望在調用setSecondState()時重新渲染此組件,而不是在調用setFirstState()或setThirdState()時重新渲染。

const ExampleComponent = () => {
     const [firstState, setFirstState] = React.useState(0);
     const [secondState, setSecondState] = React.useState(false);
     const [thirdState, setThirdState] = React.useState("");

     return (
          <div>
                Rendered
          </div>
     );
}

不要將其置於使用ref的狀態。 您可以通過更新ref.current來更新ref值,不會引起重新渲染。

const ExampleComponent = () => { 

     const firstRef = React.useRef(0);
     const [secondState, setSecondState] = React.useState(false);
     const secondRef = React.useRef("");

     const someFunction = () => {
         firstRef.current = 10;
         secondRef.current = "foo";
     }

     return (
          <div>
                Rendered
          </div>
     );
}

您可以使用shouldComponentUpdate生命周期函數。 這將返回一個布爾值,指示是否響應渲染。

在下面的示例中,當v1值更改時,它不會觸發重新渲染,而更改v2則觸發重新渲染。

 class App extends React.Component { state = { v1: 0, v2: 0 } shouldComponentUpdate(nextProps, nextState){ console.log('v1: ', nextState.v1, ', v2: ', nextState.v2); return this.state.v1 === nextState.v1 } render(){ const { v1, v2 } = this.state; return ( <div> <button onClick={() => this.setState(({ v1 }) => ({ v1: v1 + 1 }))}>{`Increase but do not render: ${v1}`}</button><br /> <button onClick={() => this.setState(({ v2 }) => ({ v2: v2 + 1 }))}>{`Increase and render: ${v2}`}</button> </div> ) } } ReactDOM.render(<App />, document.getElementById('root')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM