You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

14 lines
659 B

2 years ago
  1. import { useEffect, useState} from 'react'
  2. /* const {message, setMessage} = useState(defaultValue)
  3. 1.message 可以通过自定义传入默认初始值
  4. 2.每次修改 message 数据的时候都会自动往同步一份 */
  5. export function useLocalStorage (key, defaultValue) {
  6. const [message, setMessage] = useState(defaultValue)
  7. // 每次只要 message 变化,就会自动同步到本地 localStorage
  8. useEffect (() => {
  9. // setItem(keyname, value) 是添加键和值,如果对应的值存在,则更新该键对应的值。
  10. window.localStorage.setItem(key, message)
  11. }, [message, key])
  12. return [message, setMessage]
  13. }