1:React.memo类似于PureComponent的作用,当父类传递的props发生变化时才会重新渲染
import React, { useState } from 'react';
import Child from '../Child';
function Parent() {
const [parentCount, setParentCount] = useState(0);
console.log('父組件重新渲染--------------');
return (
<div style={{ background: 'lightseagreen' }}>
<Child />
<button type="button" onClick={() => { setParentCount(parentCount + 1); }}>父组件 +1</button>
</div>
);
}
export default Parent;
import React from 'react';
function Child() {
console.log('------------子組件重新渲染');
return (
<div style={{ background: 'pink', margin: '50px 0' }}>
<button type="button">子組件</button>
</div>
);
}
export default React.memo(Child);
2:useMemo用于减少每次组件重新渲染时重复进行复杂的计算,参数为一个函数和可选的依赖项数组,返回传入函数的调用结果。当该方法用于子类时,需要配合React.memo使用
把一些涉及计算的方法放在useMemo方法中,避免无效计算
import React, { useState, useMemo } from 'react';
import Child from '../Child';
function Parent() {
const [parentCount, setParentCount] = useState(0);
const [otherCount, setOtherCount] = useState(0);
console.log('父組件重新渲染--------------');
// 一个复杂的计算
const computedFn = (a, b) => {
console.log('----重新执行了计算----');
return a + b;
};
const computedValue = useMemo(() => {
return computedFn(parentCount, 1);
}, [parentCount]);
return (
<div style={{ background: 'lightseagreen' }}>
<Child parentCount={parentCount} computedValue={computedValue} />
<button type="button" onClick={() => { setParentCount(parentCount + 1); }}>父组件 +1</button>
<button type="button" onClick={() => { setOtherCount(otherCount + 1); }}>父组件 otherCount+1</button>
</div>
);
}
3:useCallback用于需要传递给子组件的函数,减少子组件的重复渲染,参数为一个函数和可选的依赖项数组,返回出入函数的记忆版本。当该方法需要配合React.memo使用。
import React, { useState, useCallback } from 'react';
// ...other code
const computedFn = useCallback(() => {
console.log(parentCount);
return parentCount + 1;
}, [parentCount]) ;
// ...other code
export default Parent;
import React from 'react';
function Child(props) {
const { computedValue, computedFn } = props;
console.log('------------子組件重新渲染');
return (
<div style={{ background: 'pink', margin: '50px 0' }}>
<div>
父组件传入的计算结果:
{computedValue}
</div>
<button type="button" onClick={computedFn}>子組件</button>
</div>
);
}
export default React.memo(Child);