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>
  )
}
相关推荐
是烟花哈1 小时前
【前端】React框架学习
前端·学习·react.js
qq4356947012 小时前
JavaWeb08
前端
2401_878454533 小时前
html和css的复习(1)
前端·css·html
@PHARAOH3 小时前
WHAT - git worktree 概念
前端·git
IT_陈寒4 小时前
我竟然被JavaScript的隐式类型转换坑了三天!
前端·人工智能·后端
我亚索贼六丶4 小时前
二十六. AI基础概念之如何更好的使用AI
前端
小码哥_常4 小时前
安卓启动页Logo适配秘籍:告别“奇形怪状”的展示
前端
我亚索贼六丶4 小时前
二十五.Electron 初体验与进阶
前端
当时只道寻常4 小时前
像使用 Redis 一样操作 LocalStorage
前端·前端工程化
RONIN4 小时前
UI组件库elementplus
前端