React - shouldComponentUpdate细化无效更新

发布时间 2023-03-22 21:16:50作者: Felix_Openmind
import React, { Component } from 'react'
import ReactDOM from 'react-dom/client'
import { nanoid } from 'nanoid'

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

// PureComponent实现浅比较
class MyApp01 extends React.Component {
  state = {
    list: [1, 2, 3],
  }

  handleClick = () => {
    // ✔ [..this.state.list]表示一个新的数组,内存地址已经发生改变
    // ❌ 浅比较:会导致list的内存地址,一致没有变化
    this.state.list.push(4)
    this.setState(this.state)
  }

  render() {
    const { list } = this.state
    return (
      <>
        <div>
          <button onClick={this.handleClick}>点击修改list</button>
          <Child list={list} />
        </div>
      </>
    )
  }
}

class Child extends React.PureComponent {
  shouldComponentUpdate(nextProps) {
    console.log('this.props.list => ', this.props.list)
    console.log('nextProps.list => ', nextProps.list)
    console.log(
      'nexProps.list === this.props.list ===> ',
      nextProps.list === this.props.list
    )
    if (nextProps.list === this.props.list) {
      return false
    } else {
      return true // 表示更新
    }
  }

  render() {
    const { list } = this.props
    return <h1>Child - {list}</h1>
  }
}

const divNode = (
  <div>
    <MyApp01 />
  </div>
)
root.render(divNode)