
import { atom } from 'jotai'
const countAtom = atom(0)
const countryAtom = atom('Japan')
const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])
const mangaAtom = atom({ 'Dragon Ball': 1984, 'One Piece': 1997, Naruto: 1999 })
复制代码import { useAtom } from 'jotai'
function Counter() {
  const [count, setCount] = useAtom(countAtom)
  return (
    <h1>
      {count}
      <button onClick={() => setCount(c => c + 1)}>one up</button>
复制代码主要是为了存储token,主题色等。
先定义一个atom
export const themeColorAtom = atomWithStorage('themeColor', localStorage.getItem('themeColor')||'#1890ff')
复制代码import {themeColorAtom} from '@/store'
import { useAtom } from 'jotai'
 const [color, setColor] =useAtom(themeColorAtom)
复制代码使用setColor修改变量的同时则会起到同时修改本地localstorge里面的变量的值。
import { useAtom } from 'jotai'
import { atomWithStorage } from 'jotai/utils'
const darkModeAtom = atomWithStorage('darkMode', false)
const Page = () => {
  const [darkMode, setDarkMode] = useAtom(darkModeAtom)
  return (
    <>
      <h1>Welcome to {darkMode ? 'dark' : 'light'} mode!</h1>
      <button onClick={() => setDarkMode(!darkMode)}>toggle theme</button>
    </>
  )
}
复制代码import { useAtom } from 'jotai'
import { atomWithStorage, RESET } from 'jotai/utils'
const textAtom = atomWithStorage('text', 'hello')
const TextBox = () => {
  const [text, setText] = useAtom(textAtom)
  return (
    <>
      <input value={text} onChange={(e) => setText(e.target.value)} />
      <button onClick={() => setText(RESET)}>Reset (to 'hello')</button>
    </>
  )
}
复制代码