useCallback作用:
1、防止函数组件的函数重新生成
let fn = null
const App = () => {
const Child = ({ num }) => {
const testUseCallback = useCallback(() => {
console.log(num)
}, [num])
/*
第一次为false,后面每3s输出一次,为true;每次点击按钮改变num值后输出一次false,后续输出为true
*/
console.log(fn === testUseCallback)
fn = testUseCallback
return <div>子组件</div>
}
const Parent = () => {
let timer = useRef(null)
const [count,setCount] = useState(0)
const [num,setNum] = useState(0)
useEffect(()=>{
timer.current = setInterval(() => {
setCount(count + 1)
},3000)
return clearInterval(timer.current)
},[]}
return (
<div>
<div onClick={() => setNum(num + 1)}>点击修改num值</div>
<Child num={num} count={count} />
</div>)
}
return <Parent />
render(<App {...config} />, document.querySelector('#app'))
网友评论