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