jotai
v2.11.0


访问jotai.org或npm i jotai
Jotai从简单的USESTATE替换到企业打字条应用程序。
示例:演示1 |演示2
原子代表一个状态。您需要的只是指定一个初始值,该值可能是字符串和数字,对象和数组等原始值。您可以根据需要创建尽可能多的原始原子。
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 } )它可以像React.useState一样使用:
import { useAtom } from 'jotai'
function Counter ( ) {
const [ count , setCount ] = useAtom ( countAtom )
return (
< h1 >
{ count }
< button onClick = { ( ) => setCount ( ( c ) => c + 1 ) } > one up </ button >
...可以通过将读取函数作为第一个参数创建一个新的仅读取原子。 get允许您获取任何原子的上下文值。
const doubledCountAtom = atom ( ( get ) => get ( countAtom ) * 2 )
function DoubleCounter ( ) {
const [ doubledCount ] = useAtom ( doubledCountAtom )
return < h2 > { doubledCount } </ h2 >
}您可以组合多个原子以创建派生原子。
const count1 = atom ( 1 )
const count2 = atom ( 2 )
const count3 = atom ( 3 )
const sum = atom ( ( get ) => get ( count1 ) + get ( count2 ) + get ( count3 ) )或者,如果您喜欢FP模式...
const atoms = [ count1 , count2 , count3 , ... otherAtoms ]
const sum = atom ( ( get ) => atoms . map ( get ) . reduce ( ( acc , count ) => acc + count ) )您也可以使读取函数成为异步函数。
const urlAtom = atom ( 'https://json.host.com' )
const fetchUrlAtom = atom ( async ( get ) => {
const response = await fetch ( get ( urlAtom ) )
return await response . json ( )
} )
function Status ( ) {
// Re-renders the component after urlAtom is changed and the async function above concludes
const [ json ] = useAtom ( fetchUrlAtom )
. . .在第二个参数中指定写功能。 get将返回原子的当前值。 set将更新原子的值。
const decrementCountAtom = atom (
( get ) => get ( countAtom ) ,
( get , set , _arg ) => set ( countAtom , get ( countAtom ) - 1 )
)
function Counter ( ) {
const [ count , decrement ] = useAtom ( decrementCountAtom )
return (
< h1 >
{ count }
< button onClick = { decrement } > Decrease </ button >
...只是不要定义读取功能。
const multiplyCountAtom = atom ( null , ( get , set , by ) =>
set ( countAtom , get ( countAtom ) * by ) ,
)
function Controls ( ) {
const [ , multiply ] = useAtom ( multiplyCountAtom )
return < button onClick = { ( ) => multiply ( 3 ) } > triple </ button >
}只需使写入功能成为异步功能,并在准备就绪时调用set 。
const fetchCountAtom = atom (
( get ) => get ( countAtom ) ,
async ( _get , set , url ) => {
const response = await fetch ( url )
set ( countAtom , ( await response . json ( ) ) . count )
}
)
function Controls ( ) {
const [ count , compute ] = useAtom ( fetchCountAtom )
return (
< button onClick = { ( ) => compute ( 'http://count.host.com' ) } > compute </ button >
. . .Jotai的流体界面并非偶然 - 就像承诺一样! Monads是模块化,纯净,健壮和可理解的代码的既定模式,可针对更改进行了优化。阅读有关Jotai和Monads的更多信息。