React [Performance optimization_shouldComponentUpdate, performance optimization_time slicing, performance optimization_virtual list, PropTypes for type checking, default Prop value, TypeScript] (6)

 

Table of contents

Performance optimization_shouldComponentUpdate

Performance optimization_time slicing

Performance optimization_virtual list

PropTypes for type checking

Default prop value 

TypeScript type checking 


Performance optimization_shouldComponentUpdate
 

When a component's props or state change, React will compare the latest returned element with the previously rendered element to determine whether it is necessary to update the real DOM. When they are not the same, React updates the DOM.
The shouldComponentUpdate method will be triggered before re-rendering. The default implementation always returns true, letting React perform the update.

If there are situations where your component does not need to be updated, you can return false in shouldComponentUpdate to skip the entire rendering process.
 

//ColorButtonParent.js
import React, { Component } from 'react';
import ColorButton from './ColorButton';
export default class ColorButtonParent
extends Component {
    constructor(){
        super()
        this.state={color:'#ccc',count:0}
   }
  render() {
    return (
      <div>
          <button onClick= {()=>this.setState({color:'pink'})} style={
   
   {color:this.state.color}}>变色</button>
          <button onClick= {()=>this.setState({count:this.state.count+1})} >变量</button>
       <h3>数量:{this.state.count}</h3>
        <ColorButton color= {this.state.color}/>
      </div>
   );
//ColorButton.js
import React, { Component } from 'react';

export default class ColorButton extends Component {
    shouldComponentUpdate(nextProps){
        //只有传递过来的color更改了,才更新,父组件其他状态变更了,不更新
        if(this.props.color !== nextProps.color){
            return true
       }
        return false
   }
  render() {
      console.log('ColorButton重新渲染了')
    return (
      <button style= {
   
   {color:this.props.color}}>跟着变色</button>
   );
 }
}

Performance optimization_time slicing
 

One thing we must understand is that js execution is always much faster than dom rendering . Therefore, for a large amount of data, one-time rendering can easily cause lags and freezes.
 

import React, { Component } from 'react';
export default class LargeDom extends Component {
    constructor(){
        super()
        this.state={list:[]}

   }
    componentDidMount(){
       this.setState({list:new Array(40000).fill(0)})
   }
  render() {
    return (
      <div>
         {this.state.list.map((item,index)=><li key= {index}>
             这是第{index+1}条数据
          </li>)}
      </div>
   );
 }
}
import React, { Component } from 'react';
export default class LargeDom extends
Component {
    constructor(){
        super()
        this.state={list:[]}
   }
    componentDidMount(){
       this.preList=new Array(40000).fill(0)//定义初始的40000条数据
       this.sliceTime(0)
   }

//时间分片,每一次渲染100条数据,渲染400次
    sliceTime=(times)=>{
        console.log('times',times)
        if(times==400) {
            return
       }
        setTimeout(()=>{
            const sliceList=this.preList.slice(times*100,((times+1)*100))
                    
            this.setState({list:this.state.list.concat(sliceList)})
            this.sliceTime(times+1)
       },0)
        
   }
  render() {
    return (
      <div>
          
         {this.state.list.map((item,index)=><li key= {index}>
             这是第{index+1}条数据
          </li>)}
        
      </div>
   );
 }
}

Performance optimization_virtual list
 

Virtual list is a technology that displays on demand. It is not necessary to render all list items, but only a part of the list elements in the visible area.
You can use the react-virtualized virtual scrolling library.
 

npm install react-virtualized
import React, { Component } from 'react';
import {List ,AutoSizer} from 'react-virtualized'

export default class LargeDom extends
Component {
    constructor(){
        super()
        this.state={list:[]}
   }
    componentDidMount(){
       this.setState({list:new Array(40000).fill(0)})
   }
  render() {
    return (
      <div style= {
   
   {height:'600px',border:'1px solid red'}}>
          <AutoSizer>
             {({width,height})=>{
                 return   <List
                   width={width}
                   height={height}
                 rowCount= {this.state.list.length}
                 rowHeight={50}
                 rowRenderer= {({key,index,style})=><li key={key} style={style}>
                 这是第{index+1}条数据
    
             </li>}
                 />
             }}
          </AutoSizer>      
      </div>
   );
 }
}

PropTypes for type checking
 

Components can pass data through props, and we can perform type checking on the passed data type, which is helpful to identify certain types of problems before the code is run. To perform type checking on component props, you need to reference the prop-types library to provide a series of validators:
 

import PropTypes from 'prop-types';
//PropTypesTest.js
import PropTypes from 'prop-types';

export default class PropTypesTest extends
React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
   );
 }
}
PropTypesTest.propTypes = {
  name: PropTypes.string
};

//App.js
<PropTypesTest name={
   
   {name:'xiaotong'}}/>

Tip:
When the prop value type passed in is incorrect, the JavaScript console will display a warning.
For performance reasons, propTypes is only checked in development mode.

Validators provided by propTypes:

PropTypes.array
PropTypes.bool
PropTypes.func
PropTypes.number
PropTypes.object
PropTypes.string
PropTypes.symbol
// 任何可被渲染的元素(包括数字、字符串、元素或数组)
// (或 Fragment) 也包含这些类型。
PropTypes.node
// 一个 React 元素。
PropTypes.element
// 一个 React 元素类型(即,MyComponent)。
PropTypes.elementType,
// 你也可以声明 prop 为类的实例,这里使用
// JS 的 instanceof 操作符。
PropTypes.instanceOf(Message)
// 你可以让你的 prop 只能是特定的值,指定它为
// 枚举类型。
PropTypes.oneOf(['News', 'Photos'])
// 一个对象可以是几种类型中的任意一个类型
PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
])
// 可以指定一个数组由某一类型的元素组成
PropTypes.arrayOf(PropTypes.number)
// 可以指定一个对象由某一类型的值组成
PropTypes.objectOf(PropTypes.number),
// 可以指定一个对象由特定的类型值组成
PropTypes.shape({
color: PropTypes.string,
fontSize: PropTypes.number
})
// 你可以在任何 PropTypes 属性后面加上`isRequired` ,确保
// 这个 prop 没有被提供时,会打印警告信息。
PropTypes.func.isRequired
// 任意类型的数据
PropTypes.any.isRequired

 

Default prop value
 

Default values ​​for props can be defined by configuring the specific defaultProps attribute.
 

import React from 'react';
import PropTypes from 'prop-types';
export default class PropTypesTest extends
React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
   );
 }
}
PropTypesTest.propTypes = {
  name: PropTypes.string
};
PropTypesTest.defaultProps={
  name:'默认值'
}

Tip:
Type checking also works for defaultProps.

TypeScript type checking
 

TypeScript is a programming language developed by Microsoft. It is a type superset of JavaScript and includes an independent compiler. As a typed language, TypeScript can find bugs and errors at compile time, so that such errors can be avoided when the program is run.
 

npx create-react-app my-ts-app --template typescript

import React, { Component } from 'react'


//定义props的类型
type Props={
    name:string
}
export default class Test extends
Component<Props> {
  render() {
    return (
      <div>{this.props.name}</div>
   )
 }
}
//App.js
<Test name={
   
   {name:'xiaotong'}}/>

 

Guess you like

Origin blog.csdn.net/m0_58719994/article/details/133178847