在頁(yè)面中使用了setTimout()窘拯、addEventListener()等,要及時(shí)在componentWillUnmount()中銷(xiāo)毀
使用異步組件
// lazy返回新的組件,捕獲動(dòng)態(tài)import的狀態(tài)
// Suspense根據(jù)組件狀態(tài)返回fallback中的內(nèi)容或者動(dòng)態(tài)引入的組件
import React, { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
- 使用 React-loadable 動(dòng)態(tài)加載組件
react-loadable實(shí)現(xiàn)的是代碼分割,并且在未加載完成異步組件的時(shí)候可傳入loading組件
import React from 'react';
import Loadable from 'react-loadable';
//通用的過(guò)場(chǎng)組件
const loadingComponent =()=>{
return (
<div>loading</div>
)
}
export default Loadable({
loader:import('./index.js'),
loading:loadingComponent
});
shouldComponentUpdate(簡(jiǎn)稱(chēng)SCU )、React.PureComponent彩匕、React.memo、
shouldComponentUpdate中可以自己比較props和state來(lái)限制更新的次數(shù)
PureComponent中默認(rèn)在shouldComponentUpdate添加的shallowEqual來(lái)比較props和state來(lái)更新
memo()只在props更新的時(shí)候組件進(jìn)行更新不可變值 Immutable.JS
原理:內(nèi)部采用結(jié)構(gòu)共享來(lái)避免所有節(jié)點(diǎn)拷貝帶來(lái)的性能損耗
缺陷: 容易和原生變量搞混媒区、
import Immutable from Immutable
const list = Immutable.fromJS([1,2,3,4]);
- hooks下的useMemo驼仪、useEffect
// 例如子組件
function demo({ name }) {
function changeName (name) {
return "nameChange" + name;
}
const nameWithMemo = useMemo(() => {
changeName
}, [name])
return (
<div>{nameWithMemo}</div>
)
}
const App = () => {
const [count1, setCount1] = React.useState(0)
const [count2, setCount2] = React.useState(0)
const increaseCounter1 = useCallback(() => {
setCount1(count1 => count1 + 1)
}, [])
const increaseCounter2 = useCallback(() => {
setCount2(count2 => count2 + 1)
}, [])
console.log(increaseCounter1)
return (
<>
<Counter value={count1} onClick={increaseCounter1}>Counter 1</Counter>
<Counter value={count2} onClick={increaseCounter2}>Coutner 2</Counter>
</>
)
}
ReactDOM.createPortal(child, container)
將一些組件渲染在root節(jié)點(diǎn)外掸犬,ReactDOM.createPortal(child, container)
function Modal(props) {
const ele = document.createElement("div");
useEffect(() => {
document.body.appendChild(ele);
return () => {
document.body.removeChild(ele);
}
},[props])
return reactDom.createPortal(
props.children,
ele,
)
}