一、简介
冤大头,看完Recoil简介后发现已经不推荐使用了,更推荐Jotai
Jotai 采用 Atom 风格的方式进行全局的 React 状态管理。
Atom 是Jotai中状态管理单位,它是可以更新和订阅的,当Atom被更新时,订阅了这个Atom的组件便会使用新值重新渲染
并且,更新对应的Atom 只会重新渲染订阅了这个 Atom 的组件,并不会像Context那样导致整个父组件重新渲染,所以可以做到精确渲染
jotai可以看做是Recoil的简化版本,并且可以使用TS来维护类型
二、简单使用
1、安装
# npm
npm i jotai
# yarn
yarn add jotai
# pnpm
pnpm add jotai
2、atom
原始类型的 atom 可以是后面列出的任何类型:booleans、numbers、strings、objects、arrays、sets、maps、 等。
import { atom } from 'jotai'
const countAtom = atom(0)
const countryAtom = atom('Japan')
const citiesAtom = atom(['Tokyo', 'Kyoto', 'Osaka'])
const animeAtom = atom([
{
title: 'Ghost in the Shell',
year: 1995,
watched: true
},
{
title: 'Serial Experiments Lain',
year: 1998,
watched: false
}
])
3、派生atom
派生类型的 atom 在返回自身的值之前,可以读取其它 atom 的值。
const progressAtom = atom((get) => {
const anime = get(animeAtom)
return anime.filter((item) => item.watched).length / anime.length
})
4、异步派生atom
const detailAtom = atom(async () => {
const result = await fakeFetchDetail()
return result;
})
5、使用atom
// useAtom 获取atom的值以及改变值的方法
const [anime, setAnime]=useAtom(animeAtom)
//useAtomValue 获取atom的值
const anime =useAtomValue(animeAtom)
//useSetAtom 获取改变值的方法
const setAnime =useSetAtom(animeAtom)
三、缺点
缺点与Recoil一致
由于atom的使用方法和Hooks使用方法一致,所以这种方法都不能在纯js中单独使用,会有一些限制,使用时需要传入相应的set方法