首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >jotai使用

jotai使用

作者头像
用户4792657
发布2022-07-06 14:09:15
发布2022-07-06 14:09:15
55600
代码可运行
举报
文章被收录于专栏:山海亦有归期山海亦有归期
运行总次数:0
代码可运行

jotai使用

快速使用

定义变量

代码语言:javascript
代码运行次数:0
运行
复制
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 })
复制代码

在页面中使用

代码语言:javascript
代码运行次数:0
运行
复制
import { useAtom } from 'jotai'

function Counter() {
  const [count, setCount] = useAtom(countAtom)
  return (
    <h1>
      {count}
      <button onClick={() => setCount(c => c + 1)}>one up</button>
复制代码

本地存储

主要是为了存储token,主题色等。

使用

index.ts

先定义一个atom

代码语言:javascript
代码运行次数:0
运行
复制
export const themeColorAtom = atomWithStorage('themeColor', localStorage.getItem('themeColor')||'#1890ff')
复制代码
index.tsx
代码语言:javascript
代码运行次数:0
运行
复制
import {themeColorAtom} from '@/store'
import { useAtom } from 'jotai'

 const [color, setColor] =useAtom(themeColorAtom)
复制代码

使用setColor修改变量的同时则会起到同时修改本地localstorge里面的变量的值。

官方例子
代码语言:javascript
代码运行次数:0
运行
复制
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>
    </>
  )
}
复制代码

删除/重置

代码语言:javascript
代码运行次数:0
运行
复制
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>
    </>
  )
}
复制代码
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-04-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • jotai使用
    • 快速使用
      • 定义变量
      • 在页面中使用
    • 本地存储
      • 使用
      • 删除/重置
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档