赞
踩
可用于获取 DOM 元素
- const ScrollRef = useRef(null)
- ScrollRef.current
(先回顾一下之前的 Context 知识,借用之前 ppt 和源码)
Hooks 中使用 useContext
来获取 context 的值
- // 父组件创建 context
- export const MenuContext = createContext<IMenuContext>({ index: 0 }) // 初始值
-
- // context 传递的数据
- const passedContext: IMenuContext = {
- index: currentActive ? currentActive : 0,
- onSelect: handleClick,
- }
-
- <MenuContext.Provider value={passedContext}>
- {renderChildren()}
- </MenuContext.Provider>
-
- // 子组件使用
- const context = useContext(MenuContext)
- context.onSelect(index)
useReducer 和 redux 不同
useReducer 是
useState
的代替方案,用于更复杂
的 state 变化逻辑useReducer 是
单组件
的状态管理,多组件通讯还是需要 props 传递数据redux 是
全局
的状态管理,多组件
可共享数据
(先回顾一下之前的性能优化部分的知识,借用之前 ppt 和源码)
React 默认更新
所有
子组件
Class 组件
使用 SCU 或者 PureComponent 进行优化
Hooks
里使用 useMemo 缓存数据(和 PureComponent 原理是一样的)
- // 子组件使用 memo()包裹 (对props浅层对比)
- const Child = memo(({ userInfo }) => {
- console.log('Child render ...', userInfo)
-
- return <>
- </>
- })
-
- // 父组件 用 useMemo 缓存传递的数据, 有依赖
- const userInfo = useMemo(() => {
- return { name, age = 21 }
- }, [name])
-
- <Child userInfo={userInfo}/>
在 useMemo 的基础上继续,如果是函数传递
给子组件,怎么办?
useMemo 缓存
数据
useCallback 缓存
函数
- // 子组件
- const Child = ({ onChange }) => {
- console.log('Child render ...', onChange)
-
- return <>
- </>
- }
-
- // 父组件 用 useCallback 缓存传递的函数, 依赖 []
- const onChange = useCallback(e => {
- console.log(e.target.value)
- }, [])
-
- <Child onChange={onChange}/>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。