Re: 新手让网页 act 起来: Day30 - React hooks 之 useDebugValue

前言

今天要介绍最後一个 React hook - useDebugValue ,它也是个较少使用的 hook ,且它的使用必须搭配 React dev tools 与 custom hook 。那究竟它是用来做什麽的呢?就让我们来认识认识它吧!

useDebugValue

useDebugValue 的功用在当我们开启 React dev tools 时,可以看到 custom hook 的标签。让我们直接拿昨天的范例来看看吧!

function useLocalStorageState(key, initialValue = '') {
  const [state, setState] = React.useState(() => {
    const storageValue = window.localStorage.getItem(key)
    if (storageValue) return JSON.parse(storageValue)

    return typeof initialValue === 'function' ? initialValue() : initialValue
  })


  React.useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(state))
  }, [state])

  return [state, setState]
}

function App() {
  const [name, setName] = useLocalStorageState('name', '')

  function onChangeHandler(e) {
    setName(e.target.value)
  }

  return (
    <div>
      <form>
        <label htmlFor="name">Name: </label>
        <input id="name" type="text" value={name} onChange={onChangeHandler} />
      </form>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('root'))

首先,让我打开 React dev tools 来看看 App 元件,来观察看看还没使用 useDebugValue 的状况。

再来,我们在 useLocalStorageState 中加上,useDebugValue

function useLocalStorageState(key, initialValue = '') {
  const [state, setState] = React.useState(() => {
    const storageValue = window.localStorage.getItem(key)
    if (storageValue) return JSON.parse(storageValue)

    return typeof initialValue === 'function' ? initialValue() : initialValue
  })

  React.useDebugValue('hello')

  React.useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(state))
  }, [state])

  return [state, setState]
}

可以发现 LocalStorageState 就多了 'hello' 的标签。每一次当我们使用这个 custom hook 的时候就能够给它不同的标签,方便我们在检查的时候快速的找到想找的 custom hook

function useLocalStorageState(key, initialValue = '') {
  const [state, setState] = React.useState(() => {
    const storageValue = window.localStorage.getItem(key)
    if (storageValue) return JSON.parse(storageValue)

    return typeof initialValue === 'function' ? initialValue() : initialValue
  })

  React.useDebugValue(`${key}: ${state}`)

  React.useEffect(() => {
    window.localStorage.setItem(key, JSON.stringify(state))
  }, [state])

  return [state, setState]
}

function App() {
  const [name, setName] = useLocalStorageState('name', '')
  const [count, setCount] = useLocalStorageState('count', 0) // 多设置一个 state
//.....
}

以上就是今天关於 useDebugValu 的基本认识,如果有任何问题都欢迎在下方留言!

该文章同步发布於:我的部落格


<<:  用 Python 畅玩 Line bot - 11:Sticker message

>>:  【学习笔记-JS】处理阵列的方法

Day_05 opkg套件管理

在往下继续讲其他网路架构之前,想先来介绍OpenWrt的套件管理系统。常见的Linux发行版几乎都会...

Day 15 - Rancher 与 Infrastructure as Code

本文将於赛後同步刊登於笔者部落格 有兴趣学习更多 Kubernetes/DevOps/Linux 相...

<Day17>在用API做投资前,先弄懂什麽是"量化交易"?

● 让我们来一起探究什麽是"量化交易"吧! 说到"反覆验证"...

【day5】二林&员林特色小吃

疫情前期看到千千拍摄《我们回家吧》系列 刚好跟男友回员林 所以就照着千千的推荐名单走一次罗 阳光老店...

Day11 主动情蒐-建立练习环境 metasploitable3

因为我们之後练习需要透过 metasploitable 3 当作靶机,所以要先安装 metaspl...