屏幕聚焦重新请求
警告
在这里要区分一下h5和miniprograme的聚焦定义.
- h5: 当浏览器聚焦或者tab切换当前页卡. 即visibilitychange|focus
- miniprograme: 宿主 APP 切前台, 或者进入页面. 即useDidShow
通过设置 options.refreshOnWindowFocus
,在浏览器窗口 refocus
和 revisible
时,会重新发起请求。
const { data } = useRequest(getUsername, {
refreshOnWindowFocus: true,
});
你可以点击浏览器外部,再点击当前页面来体验效果(或者隐藏当前页面,重新展示),如果和上一次请求间隔大于 5000ms,则会重新请求一次。
- React
- Vue
network/useRequest/refreshOnWindowFocus/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Field } from '@taroify/core';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';
function getUsername(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock('@name()'));
}, 1000);
});
}
export default () => {
const { data, loading } = useRequest(getUsername, {
refreshOnWindowFocus: true,
});
return (
<DemoContent title="屏幕聚焦重新请求">
<Field align="start">Username: {loading ? 'Loading' : data}</Field>
</DemoContent>
);
};
network/useRequest/refreshOnWindowFocus/index
<template>
<block>
<demo-content title="屏幕聚焦重新请求">
<view>
Username: {{ request.loading ? 'Loading...' : request.data }}</view
>
</demo-content>
</block>
</template>
<script>
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';
function getUsername() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock('@name()'));
}, 1000);
});
}
export default {
setup() {
const request = useRequest(getUsername, {
refreshOnWindowFocus: true,
});
return { request };
},
};
</script>
API
Options
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
refreshOnWindowFocus | 在屏幕重新获取焦点或重新显示时,重新发起请求 | boolean | false |
focusTimespan | 重新请求间隔,单位为毫秒 | number | 5000 |
备注
options.refreshOnWindowFocus
、options.focusTimespan
支持动态变化。