如果在一个组件中做了一些操作,需要另一个组件进行数据刷新,该怎么实现呢?需求如下图所示:

1724847232648 e712e6d7 fac0 40b5 9543 a2d62dbb0b51

非常简单!

其实在《基于 React Context 的下拉刷新机制的设计与实现 - Jeff Tian的文章 - 知乎 》中已经隐含了这个实现,但是今天想再次分享一下,给出一个直接的参考。

在上文中,给出了一个刷新机制的设计,如下图所示:

Error creating node with https://www.yuque.com/api/filetransfer/images?url=https%3A%2F%2Fbrickverse-strapi-v2.s3.us-east-1.amazonaws.com%2FUntitled_2_8b621213ee.jpg%3Fx-oss-process%3Dimage%252Fwatermark%252Ctype_d3F5LW1pY3JvaGVp%252Csize_9%252Ctext_amVmZnRpYW4uZGV2%252Ccolor_FFFFFF%252Cshadow_50%252Ct_80%252Cg_se%252Cx_10%252Cy_10&sign=d0210b5566e0944adf109c55053e53a1cf4050040df591214ed96180c709093e. Unable to fetch: https://www.yuque.com/api/filetransfer/images?url=https%3A%2F%2Fbrickverse-strapi-v2.s3.us-east-1.amazonaws.com%2FUntitled_2_8b621213ee.jpg%3Fx-oss-process%3Dimage%252Fwatermark%252Ctype_d3F5LW1pY3JvaGVp%252Csize_9%252Ctext_amVmZnRpYW4uZGV2%252Ccolor_FFFFFF%252Cshadow_50%252Ct_80%252Cg_se%252Cx_10%252Cy_10&sign=d0210b5566e0944adf109c55053e53a1cf4050040df591214ed96180c709093e --- Reason: Response code 404 (Not Found) --- Fetch details: { "attempt": 3, "method": "GET", "errorCode": "ERR_NON_2XX_3XX_RESPONSE", "responseStatusCode": 404, "responseStatusMessage": "Not Found", "requestHeaders": { "user-agent": "got (https://github.com/sindresorhus/got)", "accept-encoding": "gzip, deflate, br" }, "responseHeaders": { "date": "Tue, 17 Sep 2024 08:18:59 GMT", "content-type": "application/json; charset=utf-8", "content-length": "36", "connection": "close", "set-cookie": [ "aliyungf_tc=7567d95aff9b72fd88e7edf1c595f0f39a414b8969a25a865c9c6ce70e3fb5a9; Path=/; HttpOnly", "acw_tc=ac11000117265611392528081ec03ccb98e01e0fc2383ba5007b01dd253ffe;path=/;HttpOnly;Max-Age=1800", "receive-cookie-deprecation=1; path=/; max-age=31536000; expires=Wed, 17 Sep 2025 08:18:59 GMT; samesite=none; secure; httponly", "lang=zh-cn; path=/; max-age=31557600; expires=Wed, 17 Sep 2025 14:18:59 GMT; domain=.yuque.com; samesite=none; secure" ], "server": "spanner/1.5.0", "vary": "Origin", "x-server-id": "gzhz00k-cwbc6-sxxfc", "request-id": "0a223bee17265611392718596148", "x-cchm": "h:0,m:0", "x-xss-protection": "1; mode=block", "x-content-type-options": "nosniff", "x-download-options": "noopen", "strict-transport-security": "max-age=31536000", "x-readtime": "2", "via": "hz-crspanner-internet-prod-ea134-p9zn9-k6mnt[404]" } } ---

其中,下拉动作触发整页刷新,其实稍作变通就能实现本文最初列出的需求,即将下拉触发改成某个组件的动作触发即可。也就是刷新上下文可以在任何组件中进行获取,并在任何动作执行后进行触发调用。

所以就是:

第一步,获取刷新上下文

由于重点在触发刷新,所以关键要从刷新上下文中获取到 refresh 函数:

typescript const {refresh} = useContext(RefreshContext);

第二步,调用刷新函数

即在目标动作之后,对 refresh 进行调用即可:

typescript refresh();

完整示例

参考这个提交: feat(UNI-244): auto refresh · Jeff-Tian/weapp@cb25463 (github.com)

1724847696911 385a4e8c 20ea 4264 af6c 4097e68f7896