11. 函数式组件 与 hook

This commit is contained in:
shikong 2024-10-27 21:18:46 +08:00
parent a00d0611de
commit ca7699cd5d
Signed by: Shikong
GPG Key ID: BD85FF18B373C341

View File

@ -1,5 +1,6 @@
import React, {useEffect, useState} from "react";
import React, {useCallback, useContext, useEffect, useMemo, useRef, useState} from "react";
export let ContextParent = React.createContext({})
// 函数式组件
// 1. 没有生命周期
@ -28,7 +29,17 @@ export default function SonComponent2(props= {
count: 0,
})
// 类似 vue computed, 缓存运算结果
// 如果依赖项更新, 则重新计算
// 组件初始化时 不会 执行
let countMemo = useMemo(() => {
console.log("state.count", state.count)
return state.count
}, [state.count]);
// 模拟 componentDidUpdate
// 类似 vue 的 watch
// 组件初始化时 就会 执行
useEffect(() => {
// 当count更新时执行的操作
console.log('SonComponent2 组件后更新,执行的操作:', state);
@ -42,16 +53,23 @@ export default function SonComponent2(props= {
})
}
function revokeChangeMsg(){
// 缓存函数
// 用于优化, 避免更新时重复创建
const revokeChangeMsg = useCallback(() => {
let count = state.count
setState({
...state,
count: count > 0 ? --count : 0,
tmp: props.changeMsg(state.tmp)
})
}
}, [props, state]);
let ref = useRef()
useEffect(() => {
console.log("SonComponent2 ref", ref, ref.current)
}, []);
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
子组件2
@ -62,15 +80,25 @@ export default function SonComponent2(props= {
<hr/>
<div>
{props.msg}
<ContextParent.Provider value={{changeText: "修改msg", revokeText: "修改msg"}}>
<div>
<button onClick={changeMsg}>修改msg</button>
<button onClick={revokeChangeMsg}>撤销操作</button>
{props.msg}
<div>count: {countMemo}</div>
<Consumer ref={ref} changeMsg={changeMsg} revokeChangeMsg={revokeChangeMsg}/>
</div>
</div>
</ContextParent.Provider>
</div>
</div>
}
function Consumer(props){
let contextValue = useContext(ContextParent)
console.log("SonComponent2 Consumer contextValue", contextValue)
return <div>
<button ref={props.ref} onClick={props.changeMsg}>{contextValue.changeText}</button>
<button onClick={props.revokeChangeMsg}>{contextValue.revokeText}</button>
</div>
}