|
| 1 | +/** |
| 2 | + * desc: 同一个 `cacheKey` 的请求,是全局共享的,也就是你可以提前加载数据。利用该特性,可以很方便的实现预加载。 |
| 3 | + */ |
| 4 | +import React, { useEffect, useState } from 'react'; |
| 5 | +import { useRequest } from 'taro-hooks'; |
| 6 | +import Mock from 'mockjs'; |
| 7 | + |
| 8 | +import { AtButton } from 'taro-ui'; |
| 9 | +import { View } from '@tarojs/components'; |
| 10 | +import DocPage from '@components/DocPage'; |
| 11 | + |
| 12 | +async function getArticle(): Promise<{ data: string; time: number }> { |
| 13 | + return new Promise((resolve) => { |
| 14 | + setTimeout(() => { |
| 15 | + resolve({ |
| 16 | + data: Mock.mock('@cparagraph(10, 20)'), |
| 17 | + time: new Date().getTime(), |
| 18 | + }); |
| 19 | + }, 1000); |
| 20 | + }); |
| 21 | +} |
| 22 | + |
| 23 | +const Article = () => { |
| 24 | + const { data, loading } = useRequest(getArticle, { |
| 25 | + cacheKey: 'article', |
| 26 | + }); |
| 27 | + if (!data && loading) { |
| 28 | + return <View>loading</View>; |
| 29 | + } |
| 30 | + return ( |
| 31 | + <> |
| 32 | + <View>Latest request time: {data?.time}</View> |
| 33 | + <View>{data?.data}</View> |
| 34 | + </> |
| 35 | + ); |
| 36 | +}; |
| 37 | + |
| 38 | +const PreloadRequest = () => { |
| 39 | + const [state, setState] = useState<boolean>(false); |
| 40 | + const { run } = useRequest(getArticle, { |
| 41 | + cacheKey: 'article', |
| 42 | + manual: true, |
| 43 | + }); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + if (!state) { |
| 47 | + run(); |
| 48 | + } |
| 49 | + }, [state, run]); |
| 50 | + |
| 51 | + return ( |
| 52 | + <DocPage title="useRequest 请求" panelTitle="预加载"> |
| 53 | + <View>When the article hidden, the article data is preloaded.</View> |
| 54 | + <AtButton |
| 55 | + type="primary" |
| 56 | + onClick={() => setState(!state)} |
| 57 | + customStyle={{ marginTop: '10px' }} |
| 58 | + > |
| 59 | + show/hidden |
| 60 | + </AtButton> |
| 61 | + {state && <Article />} |
| 62 | + </DocPage> |
| 63 | + ); |
| 64 | +}; |
| 65 | + |
| 66 | +export default PreloadRequest; |
0 commit comments