日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

解決react組件渲染兩次的問題_React

作者:神才飛揚 ? 更新時間: 2022-09-29 編程語言

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

欄目分類
最近更新