React?component.forceUpdate()強制重新渲染方式
component.forceUpdate()強制重新渲染
component.forceUpdate()
一個不常用的生命周期方法,它的作用就是強制刷新
官網(wǎng)解釋如下
默認情況下,當組件的 state 或 props 發(fā)生變化時,組件將重新渲染。
如果 render() 方法依賴于其他數(shù)據(jù),則可以調(diào)用 forceUpdate() 強制讓組件重新渲染。
調(diào)用 forceUpdate() 將致使組件調(diào)用 render() 方法,此操作會跳過該組件的 shouldComponentUpdate()。
但其子組件會觸發(fā)正常的生命周期方法,包括 shouldComponentUpdate() 方法。
如果標記發(fā)生變化,React 仍將只更新 DOM。
通常你應該避免使用 forceUpdate(),盡量在 render() 中使用 this.props 和 this.state。
通常來說
我們應該用 setState() 更新數(shù)據(jù),從而驅(qū)動更新。
所以用到 component.forceUpdate() 的情況并不多
class App extends React.Component { constructor(props) { super(props); console.log("constructor") this.onClickHandler = this.onClickHandler.bind(this); } componentWillMount() { console.log("componentWillMount") } componentDidMount() { console.log("componentDidMount") } componentWillUnmount() { console.log("componentWillUnmount") } componentWillReceiveProps() { console.log("componentWillReceiveProps") } shouldComponentUpdate() { console.log("shouldComponentUpdate") return true } componentWillUpdate() { console.log("componentWillUpdate") } componentDidUpdate() { console.log("componentDidUpdate") } onClickHandler() { console.log("onClickHandler") this.forceUpdate(); } render() { console.log("render") return ( <button onClick={this.onClickHandler}> click here </button> ); } } ReactDOM.render(<App />, document.getElementById("react-container") );
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
用React實現(xiàn)一個完整的TodoList的示例代碼
本篇文章主要介紹了用React實現(xiàn)一個完整的TodoList的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10react執(zhí)行【npx create-react-app my-app】出現(xiàn)常見錯誤的解決辦法
文章主要介紹了在使用npx創(chuàng)建React應用時可能遇到的幾種常見錯誤及其解決方法,包括缺少依賴、網(wǎng)絡問題和npx解析錯誤等,并提供了相應的解決措施,此外,還提到了使用騰訊云云產(chǎn)品來支持React應用開發(fā)2024-11-11React+umi+typeScript創(chuàng)建項目的過程
這篇文章主要介紹了React+umi+typeScript創(chuàng)建項目的過程,結(jié)合代碼介紹了項目框架搭建的方式,本文給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02React函數(shù)式組件Hook中的useState函數(shù)的詳細解析
Hook 就是 JavaScript 函數(shù),這個函數(shù)可以幫助你鉤入(hook into) React State以及生命周期等特性,這篇文章主要介紹了React Hook useState函數(shù)的詳細解析的相關資料,需要的朋友可以參考下2022-10-10React Native 自定義下拉刷新上拉加載的列表的示例
本篇文章主要介紹了React Native 自定義下拉刷新上拉加載的列表的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03