useRecoilStateLoadable(state)
此钩子可用于读取异步 selector 的值。为获取到指定状态值,此钩子将隐含地订阅对应组件。
与 useRecoilState() 不同,当读取异步 selector 时,这个钩子不会抛出一个 Error 或Promise (为了能与 React Suspense 共存)。相反,这个钩子会返回一个 Loadable 对象的值以及 setter 回调。
function useRecoilStateLoadable<T>(state: RecoilState<T>): [Loadable<T>, (T | (T => T)) => void]返回一个 Loadable 的当前状态与接口:
state: 表示 selector 的状态。可能的值是hasValue、hasError、loading。contents:Loadable所代表的值。如果状态是hasValue,它就是实际的值;如果状态是hasError,它就是被抛出的Error对象,如果状态是loading,那么它就是Promise。
示例#
function UserInfo({userID}) { const [userNameLoadable, setUserName] = useRecoilStateLoadable(userNameQuery(userID)); switch (userNameLoadable.state) { case 'hasValue': return <div>{userNameLoadable.contents}</div>; case 'loading': return <div>Loading...</div>; case 'hasError': throw userNameLoadable.contents; }}