美文网首页
React usePersistedState hook

React usePersistedState hook

作者: ikonan | 来源:发表于2022-07-26 19:28 被阅读0次

返回一个持久化在localStorage中的有状态值,以及一个更新它的函数。

  • 使用useState()钩子将该值初始化为defaultValue。
  • 使用useRef()钩子创建一个引用,该引用将保存Window.localStorage中的值的名称。
  • 使用三个useEffect()钩子的实例分别进行初始化、值更改和名称更改。
  • 当组件第一次挂载时,如果有存储值,则使用Storage.getItem()来更新值,或者使用Storage.setItem()来持久化当前值。
  • 当value被更新时,使用Storage.setItem()来存储新值
  • 当名称更新时,使用Storage.setItem()创建新的密钥,更新nameRef并使用Storage.removeItem()从windows . localstorage中删除之前的密钥。
    注意:该钩子是用于原始值(即不是对象)的,不考虑对Window的更改。localStorage由于其他代码。这两个问题都很容易处理(例如JSON序列化和处理“存储”事件)。
import { useState,useRef, useEffect } from "react"

const usePersistedState  = (name: string, defaultValue: string) => {
  const [value, setValue] = useState(defaultValue)
  const nameRef = useRef(name)

  useEffect(()=>{
    try {
      const storedValue = localStorage.getItem(name)
      if (storedValue !== null) {
        setValue(storedValue)
      } else {
        localStorage.setItem(name, defaultValue)
      }
    } catch  {
      setValue(defaultValue)
    }
  }, [])

  useEffect(()=>{
    try {
        localStorage.setItem(nameRef.current, value)
    } catch  {
    }
  }, [value])

  useEffect(()=>{
    const lastName = nameRef.current;
    if (name !== lastName) {
      try {
        localStorage.setItem(name, value)
        nameRef.current = name;
        localStorage.removeItem(lastName)
      } catch  {
      }
    }
  }, [name])

  return [ value, setValue]
}

export default usePersistedState

Example

const MyComponent = ({ name }) => {
  const [val, setVal] = usePersistedState(name, 10);
  return (
    <input
      value={val}
      onChange={e => {
        setVal(e.target.value);
      }}
    />
  );
};

const MyApp = () => {
  const [name, setName] = React.useState('my-value');
  return (
    <>
      <MyComponent name={name} />
      <input
        value={name}
        onChange={e => {
          setName(e.target.value);
        }}
      />
    </>
  );
};

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

相关文章

  • React usePersistedState hook

    返回一个持久化在localStorage中的有状态值,以及一个更新它的函数。 使用useState()钩子将该值初...

  • React hook 10种 Hook

    React hook 10种 Hook (详细介绍及使用) React Hook是什么?React官网是这么介绍的...

  • 学习react hook的总结

    react16推出了react hook,react hook使得functional组件拥有了class组件的一...

  • react-hook-form使用

    官网地址:https://react-hook-form.com/[https://react-hook-form...

  • react hook介绍

    react hook是什么 react hook是react中引入新特性,它可以让react函数组件也拥有状态;通...

  • React Hook介绍与使用心得

    关于React Hook React Hook 对于React来说无疑是一个伟大的特性,它将React从类组件推向...

  • React Hook

    Through 4 questions introduce React Hook What is Hook? In...

  • react-hook

    react-hook

  • react hook入门

    一、react hook介绍 Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情...

  • React Hooks - 学习笔记

    React Hooks Hook 是能让你在函数组件中“钩入” React 特性的函数。 State Hook u...

网友评论

      本文标题:React usePersistedState hook

      本文链接:https://www.haomeiwen.com/subject/qsooirtx.html