網站首頁 編程語言 正文
react組件渲染兩次
可能會有人問,問什么我的組件明明是就讓渲染一次,但是實際上卻渲染兩次呢?其實我也遇到了這個問題,那么下面我提出一種解決這個問題的一種方法。
如果你使用了react-router低于4.x版本中的hashHistory,那么問題就來了,出現這種情況的原因是因為router中進行了一次push和一次pop,所以出現兩次渲染,
你只需要在shouldComponentUpdate()這個生命周期鉤子中做一個判斷就好了:
return (this.props.router.location.action === 'PUSH')
或者
return (this.props.router.location.action === 'POP');
只要二選一即可解決渲染兩次的問題。?
react總結之避免不必要的重復渲染
類組件PureComponent
適當的使用PureComponent創建組件可以提高性能,在使用類組件的時侯,繼承PureComponent組件,它是依賴于傳遞給組件的props進行淺比較,當props發生改變的時候,才會重新渲染組件,既然是淺比較,那么在state和props每次都發生改變的額時候,還要使用PureComponent就會對性能產生負面的影響了!
React.memo()
React.memo()和PureComponent很相似,PureComponent是一個類,React.memo()是一個函數組件,它有兩個參數,第一個參數是純函數的組件,第二個參數是true或者false,用于控制是否刷新組件!
shouldComponmentUpdate
類組件的的生命周期函數,當返回值是false的時候,視圖不做更新,否則更新!
使用插件seamless-immutable
1.引入import Immutable from 'seamless-immutable';
2.初始化state
?? ?this.state = { ?? ??? ??? ??? ??? ?list: Immutable([]); ?? ?}
3.修改state
?? ?this.setState({ ?? ??? ??? ??? ?list: Immutable(items); ?? ?})
使用插件pure-render-decorator
import React from 'react'; import pureRender from 'pure-render-decorator'; // es7才支持裝飾器,這邊需要配置babel @pureRender class List extends React.Component { render() { const {list} = this.props; return ( <> { list.map((item) => { return ( <div key={item.id}> <div>{item.code}</div> </div> ); }) } </> ); } } export default List;
原文鏈接:https://blog.csdn.net/Deng_gene/article/details/78394864
相關推薦
- 2022-06-16 Python數據結構之遞歸可視化詳解_python
- 2023-07-08 vs編譯運行報錯:未聲明的標識符
- 2022-06-16 如何使用shell獲取進程名的內存以及CPU利用率_linux shell
- 2022-10-08 Pandas數據分析-pandas數據框的多層索引_python
- 2022-03-22 聚合函數和group?by的關系(理解group by 和聚合函數)
- 2024-01-15 mybatis中@Results,@ResultMap注解使用
- 2022-06-02 基于Android?Flutter編寫貪吃蛇游戲_Android
- 2022-02-04 Win10 無法保存對hosts權限所作的更改 拒絕訪問
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支