useRecoilValueLoadable(state)
此 hook 用来读取异步 selector 的值。使用此 hook 会使组件隐式地订阅给定的 state。
与 useRecoilValue() 不同,当此 hook 从异步 selector(为了和 React Suspense 一起工作)读取数据时,不会抛出 Error 或 Promise,它会返回一个 Loadable 对象。
function useRecoilValueLoadable<T>(state: RecoilValue<T>): Loadable<T>
返回一个具有以下接口的 Loadable:
state:表示 selector 的状态。可选的值有'hasValue','hasError','loading'。contents:此值代表Loadable的结果。如果状态为hasValue,则值为实际结果;如果状态为hasError,则会抛出一个错误对象;如果状态为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;
}
}