企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
``` import React, { Component } from 'react' class Foo extends Component { // 加上这个后,会比较传入的 props 值,如果前后一致,则不渲染 shouldComponentUpdate(nextProps, nextState) { if (nextProps.name === this.props.name) { return false } return true } render() { console.log('foo render') return null } } export default class App extends Component { state = { count: 0 } render() { return ( <div> // 原本点击事件触发时,Foo组件会重新渲染 <button onClick={() => this.setState({count: this.state.count+1})} >add</button> <Foo name="Mike"/> </div> ) } } ``` 或者使用PureComponent 声明组件 ``` import React, { Component, PureComponent } from 'react' class Foo extends PureComponent { render() { console.log('foo render') return null } } ``` 但是PureComponent只会对比传入的属性第一级,不会对比属性内部,如下,传入 Foo组件的person中age发生了变化,但是Foo组件没有重新渲染 ``` import React, { Component, PureComponent } from 'react' // PureComponent 只会对比传入属性的对比,不会判断内部属性 class Foo extends PureComponent { render() { console.log('foo render') return <div>{this.props.person.age}</div> } } export default class App extends Component { state = { count: 0, person: { age: 1 } } render() { const person = this.state.person return ( <div> <button onClick={() => {person.age++;this.setState({person})}} >add</button> <Foo person={person}/> </div> ) } } ``` 或者用 memo 包裹无状态组件,相当于 PureComponent ``` const Foo = memo((props) => { console.log('foo render') return <div>{props.person.age}</div> }) ```