在上一篇文章中,用useEffect模擬生命周期componentDidUpdate
時(shí)有一個(gè)小小的問題忱叭,就是組件還沒更新就已經(jīng)打印出了n的值,看代碼:
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>
<script type="text/babel">
const Demo = (props)=> {
const [n,setN] = React.useState(0)
const onClick = ()=> {
setN(n+1)
}
React.useEffect(()=>{
console.log('n變了')
},[n])
return<div>
<h1>{n}</h1>
<button onClick={onClick}>點(diǎn)我+1</button>
</div>
}
const rootElement = document.getElementById("app")
ReactDOM.render(<Demo />, rootElement);
</script>
</body>
</html>
應(yīng)該是組件更新了數(shù)據(jù)才打印出n今艺,而不是一渲染就打印出n韵丑。類組件卻沒有出現(xiàn)這樣的問題,可以通過下面的代碼解決這個(gè)問題
const Demo = (props)=> {
const [n,setN] = React.useState(0)
const onClick = ()=> {
setN(n+1)
}
const useUpdate = (fn,dep)=> {
const [count,setCount] = React.useState(0)
React.useEffect(()=> {
setCount(x => x+1)
},[dep])
React.useEffect(()=> {
if(count>1) {
fn()
}
},[count,fn])
}
useUpdate(()=> {
console.log('n變了');
},n)
return<div>
<h1>{n}</h1>
<button onClick={onClick}>點(diǎn)我+1</button>
</div>
}
const rootElement = document.getElementById("app")
ReactDOM.render(<Demo />, rootElement);
</script>
我們可以把const useUpdate.....
封裝到一個(gè)單獨(dú)的組件虚缎,使用的時(shí)候引用撵彻,調(diào)用的時(shí)候用useUpdate(()
調(diào)用钓株,最后看一下效果
一開始渲染并不會(huì)打印n變了
,當(dāng)點(diǎn)擊之后變?yōu)槭谴蛴?code>n變了