• React整理总结(三)


    1.props和state的更新

    • 父组件重新render时,所有的子组件也会调用render()函数。shouldComponentUpdate(nextProp, nextState)
    shouldComponentUpdate(nextProps, nextState) {
    	if (equal(nextProps, this.props) && equal(nextState, this.state)){
    		return false
    	} else {
    		return true;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • PureComponent。只是对props和state进行了浅层比较
    • React.memo(),针对函数组件

    2.ref获取原生DOM

    • 字符串 this.refs.domRef |
    • 创建ref this.titleRef = React.createRef() |
    • 函数返回
      this.elRef = el} />
    • ref可以直接获取类组件实例,
    • ref获取函数式组件,需要使用forwardRef.
    const MyComponent = React.forwardRef(function (props, ref){
    return <div ref={ref} /> 
    })
    
    • 1
    • 2
    • 3

    3.高阶组价

    • 高阶函数:接受函数作为参数或者返回值为函数
    • 高阶组件(HOC):接受组件作为参数,并且返回新组件
      增强props
      配合context使用,传递state
      登录鉴权
      生命周期劫持

    4. Portals与Fragment

    createPortal(content, target)将content内容挂载到target上

    // html的body, 正常内容都是挂在root下
    <div id="root"></div>
    <div id="modal"></div>
    
    // Modal组件
    import React, {PureComponent } from “react”;
    import { createPortal } from 'react-dom';
    export default class Modal extends PureComponent {
    	constructor(props){
    		super(props);
    	}
    	render(){
    		return createPortal(this.props.children, document.querySelector("#modal"));	
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • Fragment, 短语法<>, 添加key时无法使用短语法

    5. 严格模式StrictMode

    • 识别不安全的生命周期
    • 使用过时的ref APi
    • 检查意外的副作用,constructor会被调用两次,生产模式不会
    • 检查废弃的findDOMNode函数
    • 检查过时的context api
  • 相关阅读:
    MediaPlayer
    【前端手写】call和apply方法
    Spark 基础教程:wordcount+Spark SQL
    为什么六位数高薪仍无法让技术人员感到满足?
    欧盟人工智能立法提案的核心思想 及未来影响分析
    FastJson2中FastJsonHttpMessageConverter找不到类问题
    Taro模拟table表格搭配react实现方式
    Vue3 ref函数和reactive函数
    es: java->count统计、distinct去重
    js刷题常用基础函数&常用快捷键
  • 原文地址:https://blog.csdn.net/xaishujin/article/details/134430212