场景问题:父组件传给子组件的值,可能会变也可能不会变,为了减少内存消耗,需要到达,当传给子组织值改变时,才重新渲染子组件,否则不渲染子组件,只会部分渲染(变化的)父组件。
关键点:生命周期钩子函数:shouldComponentUpdate(nextProps,nextState)
只需要在shouldComponentUpdate中进行判断下一次传的值是否与本次值一致,在做相应的步骤。
父组件parent.jsx
import React from "react";
import Child from "./chid";
/**
* 技术例子
*
* 定时器
* 网络请求
* 事件监听
* 在组件被销毁都应得到相应的处理
*
*/
const MyAPI = {
count: 0,
subscribe(cb) {
this.intervalId = setInterval(() => {
this.count += 1
cb(this.count)
}, 1000)
},
unSubscribe() {
clearInterval(this.intervalId);
this.reset();
},
reset() {
this.count = 0;
}
}
export default class Preant extends React.Component {
state = {
count: 0
}
componentDidMount() {
MyAPI.subscribe((currentCount) => {
this.setState({
count: currentCount
})
})
}
componentWillUnmount() {
MyAPI.unSubscribe();
}
render() {
console.log('parent-->render');
let num = 1;
return (
<div>
Parent:{this.state.count}
< Child num={num+this.state.count} />
</div>
)
}
}
子组件child.jsx
import React from "react";
class Child extends React.Component {
//进行判断【关键点】
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.num === this.props.num) {
return false;
}
return true;
}
render() {
console.log('child-->render');
return (
<div >
Child:{this.props.num}
</div>
);
}
}
export default Child;