import React from "react";
function memo() {
let template,cache_data;
return function (props) {
if(cache_data===props.data){
return template;
}else{
cache_data=props.data;
return template=<React.Fragment>
{
function () {
console.log("这里只会在加载时触发,更新不会触发");
return props.data.toString();
}()
}
</React.Fragment>
}
}
}
export const Child=memo();
这是我的子组件代码,但是当父组件传入的data不发生改变时,组件是不会触发更新操作的。
由于我用的是react hooks,也就没有shouldComponentUpdate,但是react依然能跳过更新,所以我想知道这是怎么跳过的?
发现是我自己想错了,其实只是跳过了jsx生成Component的环节,而diff更新还在执行,设置useEffect话依旧会执行。
如果要跳过更新,需要用React.memo方法,此时useEffect也不会执行,即会直接跳过该组件。
那应该是cache_data===props.data 的原因。可能没走else