当前位置:   article > 正文

React 其他 Hooks

React 其他 Hooks

其他 Hooks

useRef

可用于获取 DOM 元素

  1.  const ScrollRef = useRef(null)
  2.  ScrollRef.current

useContext

(先回顾一下之前的 Context 知识,借用之前 ppt 和源码)

Hooks 中使用 useContext获取 context 的值

  1.  // 父组件创建 context
  2.  export const MenuContext = createContext<IMenuContext>({ index: 0 }) // 初始值
  3.  ​
  4.  // context 传递的数据
  5.  const passedContext: IMenuContext = {
  6.      index: currentActive ? currentActive : 0,
  7.      onSelect: handleClick,
  8.  }
  9.  ​
  10.  <MenuContext.Provider value={passedContext}>
  11.     {renderChildren()}
  12.  </MenuContext.Provider>
  13.  ​
  14.  // 子组件使用
  15.  const context = useContext(MenuContext)
  16.  context.onSelect(index)

useReducer

useReducer 和 redux 不同

  • useReducer 是 useState 的代替方案,用于更复杂的 state 变化逻辑

  • useReducer 是单组件的状态管理,多组件通讯还是需要 props 传递数据

  • redux 是全局的状态管理,多组件可共享数据

useMemo

(先回顾一下之前的性能优化部分的知识,借用之前 ppt 和源码)

  • React 默认更新所有子组件

  • Class 组件使用 SCU 或者 PureComponent 进行优化

  • Hooks 里使用 useMemo 缓存数据(和 PureComponent 原理是一样的)

  1.  // 子组件使用 memo()包裹 (对props浅层对比)
  2.  const Child = memo(({ userInfo }) => {
  3.   console.log('Child render ...', userInfo)
  4.      
  5.      return <>
  6.       </>
  7.  })
  8.  ​
  9.  // 父组件 用 useMemo 缓存传递的数据, 有依赖
  10.  const userInfo = useMemo(() => {
  11.   return { name, age = 21 }
  12.  }, [name])
  13.  ​
  14.  <Child userInfo={userInfo}/>

useCallback

在 useMemo 的基础上继续,如果是函数传递给子组件,怎么办?

  • useMemo 缓存数据

  • useCallback 缓存函数

  1.  // 子组件
  2.  const Child = ({ onChange }) => {
  3.   console.log('Child render ...', onChange)
  4.      
  5.      return <>
  6.       </>
  7.  }
  8.  ​
  9.  // 父组件 用 useCallback 缓存传递的函数, 依赖 []
  10.  const onChange = useCallback(e => {
  11.   console.log(e.target.value)
  12.  }, [])
  13.  ​
  14.  <Child onChange={onChange}/>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/629973
推荐阅读
相关标签
  

闽ICP备14008679号