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的更多信息。