react重新渲染以及避免不必要的渲染

触发react重新渲染

类组件触发重新渲染

1、setState

2、context

3、props

4、forceUpdate

函数式组件重新渲染

1、useState

2、props

避免不必要的渲染

类组件避免不必要的渲染

1、React.PureComponent/shouldComponentUpdate

函数式组件避免不必要的渲染

1、React.memo

2、useMemo(缓存变量)

3、useCallback(缓存函数)

context在类组件和函数式组件中的使用

创建context对象

javascript 复制代码
import { createContext } from 'react'
const contextObj = createContext()
const { Provider, Consumer } = context

注入数据

javascript 复制代码
function APP() {

    ...
    ...
    ...

    return (
        <provide value={name: 'xiaoliu'}>
            <div></div>
        </Provide>
    )
}
类组件
javascript 复制代码
class Son2 extends Component {
  static contextType = context
  render() {
    const { name } = this.context
    return (
      <>
        我是Son,我拿到的数据是:{name}
      </>
    )
  }
}
函数式组件

1、通过Consume拿到数据

javascript 复制代码
const Son1 = () => {
  return (
    <Consumer>
      {({ name }) => (
        <div>
          我是Son,我拿到的数据是:{name}
        </div>
      )}
    </Consumer>
  )
}

2、 通过useContext 方式

javascript 复制代码
const Son3 = () => {
  const { name } = useContext(context)
  return (
    <div>
      我是Son1,我拿到的数据是:{name}
    </div>
  )
}
相关推荐
碎_浪3 小时前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain4 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
多加点辣也没关系5 小时前
JavaScript|第4章:类型转换
开发语言·javascript
yqcoder5 小时前
httpOnly 是什么,又有什么用?
开发语言·前端·javascript
IT_陈寒5 小时前
Java的Stream.parallel()把我CPU跑爆了,这种优化要谨慎
前端·人工智能·后端
小皮虾5 小时前
小程序首页性能优化实战:从 4 秒到 1.8 秒
前端·微信小程序
烬羽5 小时前
还在手动拼路径、写回调地狱?一文吃透 Node.js 的 path 和 fs
javascript·程序员·node.js
山河木马5 小时前
GPU自动处理专题1-裁剪到底在裁什么(裁剪)
前端·webgl·计算机图形学
奔跑的蜗牛ing5 小时前
CentOS Nginx 安装与静态文件服务器配置指南
前端·面试·架构