跳到主要內容

useRecoilValueLoadable(state)

此掛勾用於讀取非同步選取器的值。此掛勾會將元件訂閱至給定的狀態。

useRecoilValue() 不同,此掛勾在從非同步選取器讀取資料時,不會擲回 ErrorPromise(為了使用 React Suspense)。反之,此掛勾會傳回 Loadable 物件。

針對根據 Recoil 狀態突變的 React 18 轉場,請使用 useRecoilValueLoadable_TRANSITION_SUPPORT_UNSTABLE() 實驗性支援。


function useRecoilValueLoadable<T>(state: RecoilValue<T>): Loadable<T>
  • state可能有一些非同步操作的 atomselector。傳回的載入項的狀態會取決於所提供的狀態選取器的狀態。

傳回具有介面的目前狀態 Loadable

  • state:表示選取器的狀態。可能的值為 'hasValue''hasError''loading'
  • contents:此 Loadable 所表示的值。如果狀態為 hasValue,則它為實際值;如果狀態為 hasError,則為拋出的 Error 物件;如果狀態為 loading,則為值的一個 Promise

範例

function UserInfo({userID}) {
const userNameLoadable = useRecoilValueLoadable(userNameQuery(userID));
switch (userNameLoadable.state) {
case 'hasValue':
return <div>{userNameLoadable.contents}</div>;
case 'loading':
return <div>Loading...</div>;
case 'hasError':
throw userNameLoadable.contents;
}
}