亲测好用~~~~mark帖,如有侵权,联系删除
国际惯例原出处:https://codepen.io/nange/pen/PGYBBw/
国际惯例贴代码:
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
return false;
}
const keysA = Object.keys(objA);
const keysB = Object.keys(objB);
if (keysA.length !== keysB.length) {
return false;
}
const bHasOwnProperty = hasOwnProperty.bind(objB);
for (let i = 0; i < keysA.length; i++) {
const keyA = keysA[i];
if (objA[keyA] === objB[keyA]) {
continue;
}
// special diff with Array or Object
if (_.isArray(objA[keyA])) {
if (!_.isArray(objB[keyA]) || objA[keyA].length !== objB[keyA].length) {
return false;
} else if (!_.isEqual(objA[keyA], objB[keyA])) {
return false;
}
} else if (_.isPlainObject(objA[keyA])) {
if (!_.isPlainObject(objB[keyA]) || !_.isEqual(objA[keyA], objB[keyA])) {
return false;
}
} else if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) {
return false;
}
}
return true;
}
function shallowCompare(instance, nextProps, nextState) {
return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState);
}
function shouldComponentUpdate(nextProps, nextState) {
return shallowCompare(this, nextProps, nextState);
}
/* eslint-disable no-param-reassign */
function pureRenderDecorator(Component) {
//覆盖了component中的shouldComponentUpdate方法
Component.prototype.shouldComponentUpdate = shouldComponentUpdate;
return Component;
}
/*
* Components1
*/
class Components1 extends React.Component {
render() {
if(!this.count){
this.count = 1;
}else{
this.count++;
}
return (
<span>
Component1渲染了<b style={{color:"red",}}>{this.count}</b>次
<br />
{
this.props.data && this.props.data.map(v=>{
return (
<div>
{v}
</div>
)
})
}
</span>
)
}
}
/*
* Components2
*/
class Components2 extends React.Component {
render() {
if(!this.count){
this.count = 1;
}else{
this.count++;
}
return (
<span>
Component2渲染了<b style={{color:"red",}}>{this.count}</b>次
<br />
</span>
)
}
}
/*
* 最上层Component
*/
class Components extends React.Component {
constructor(props){
super(props);
this.state = {
data: [
1,2,4,
],
}//初始化,要不还会渲染多一次的
}
refresh(){
return (e)=>{
this.setState({
data: [
1,2,3,
]
})
}
}
render() {
var Com1 = pureRenderDecorator(Components1);
return (
<div>
Component-><Com1 data={this.state.data}/>
<br />
Component-><Components2 />
<br />
<button onClick={this.refresh()}>
刷新Component
</button>
</div>
)
}
}
/*
* Render the above component into the div#app
*/
ReactDOM.render(<Components />, document.getElementById('app'));