React - shouldComponentUpdate() 控制子组件是否随着父组件更新

import React, { Component } from 'react'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'

const root = ReactDOM.createRoot(document.getElementById('root'))

// React - 更新机制
// 1. 组件更新,默认会导致所有后代组件更新
// 2. 组件更新,默认不会影响兄弟组件

// 性能优化原则:
// 1. 功能第一
// 2. 性能第二

// 性能优化手段
// 1. 不需要渲染的数据,不要存放在state中
// 2. 使用shouldComponentUpdate避免出现无效更新

class MyApp01 extends React.Component {
  state = {
    count: 0,
  }

  render() {
    const { count } = this.state
    return (
      <>
        <div>
          <h1>count: {count}</h1>
          <button
            onClick={() =>
              this.setState({
                count: count + 1,
              })
            }
          >
            点我修改count
          </button>
        </div>
        <ChildCom count={count} />
      </>
    )
  }
}

class ChildCom extends React.Component {
  // 🔥🍅🤴🏻🟦 shouldComponentUpdate()函数的使用 ★
  // 更新之前
  shouldComponentUpdate() {
    // 通过返回true或false,决定是否更新
    // 返回true 表示更新
    // 返回false 表示不更新
    return false
  }

  // 更新中
  render() {
    console.log('【ChildCom】render 执行 => ')
    return <div>ChildCom this.props.count: {this.props.count}</div>
  }

  // 更新后
  componentDidUpdate() {
    console.log('ChildCom被更新了....')
  }
}
const divNode = (
  <div>
    <MyApp01 />
  </div>
)
root.render(divNode)

posted @ 2023-03-22 14:27  Felix_Openmind  阅读(302)  评论(0)    收藏  举报
*{cursor: url(https://files-cdn.cnblogs.com/files/morango/fish-cursor.ico),auto;}