web前端全系列 教程
1839个小节阅读:2242.8k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
当一个组件的 props 或 state 变更,React 会将最新返回的元素与之前渲染的元素进行对比,以此决定是否有必要更新真实的 DOM。当它们不相同时,React 会更新该 DOM
shouldComponentUpdate
方法会在重新渲染前被触发。其默认实现总是返回 true
,让 React 执行更新。
如果有些情况下你的组件不需要更新,你可以在 shouldComponentUpdate
中返回 false
来跳过整个渲染过程。
xxxxxxxxxx
//ColorButtonParent.js
import React, { Component } from 'react';
import ColorButton from './ColorButton';
export default class ColorButtonParent extends Component {
constructor(){
super()
this.state={
color:'#ccc',
count:0
}
}
render() {
return (
<div>
<button onClick={()=>this.setState({color:'pink'})} style={{color:this.state.color}}>变色</button>
<button onClick={()=>this.setState({count:this.state.count+1})} >变量</button>
<h3>数量:{this.state.count}</h3>
<ColorButton color={this.state.color}/>
</div>
);
xxxxxxxxxx
//ColorButton.js
import React, { Component } from 'react';
export default class ColorButton extends Component {
shouldComponentUpdate(nextProps){
//只有传递过来的color更改了,才更新,父组件其他状态变更了,不更新
if(this.props.color !== nextProps.color){
return true
}
return false
}
render() {
console.log('ColorButton重新渲染了')
return (
<button style={{color:this.props.color}}>跟着变色</button>
);
}
}
实时效果反馈
1. 下列说法错误的是:
A shouldComponentUpdate
默认返回true
B 组件props或者state发生变更的时候会调用shouldComponentUpdate
C shouldComponentUpdate
返回false代表停止更新
D shouldComponentUpdate
返回true代表停止更新
答案
1=>D