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>
  )
}
相关推荐
冬奇Lab5 小时前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent
zhangxingchao5 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒7 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic8 小时前
SwiftUI 手势笔记
前端·后端
橙子家9 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518139 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州9 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic11 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘11 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈