轮询
通过设置 options.pollingInterval
,进入轮询模式,useRequest
会定时触发 service 执行。
const { data, run, cancel } = useRequest(getUsername, {
pollingInterval: 3000,
});
例如上面的场景,会每隔 3000ms 请求一次 getUsername
。同时你可以通过 cancel
来停止轮询,通过 run/runAsync
来启动轮询。
你可以通过下面的示例来体验效果
- React
- Vue
network/useRequest/polling/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Button, Flex, Field } from '@taroify/core';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';
function getUsername(): Promise<string> {
console.log('polling getUsername');
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock('@name()'));
}, 1000);
});
}
export default () => {
const { data, loading, run, cancel } = useRequest(getUsername, {
pollingInterval: 1000,
pollingWhenHidden: false,
});
return (
<DemoContent title="轮询">
<Field align="start">Username: {loading ? 'Loading' : data}</Field>
<Flex align="center" gutter={10}>
<Flex.Item span={12}>
<Button
loading={loading}
color="primary"
size="small"
block
onClick={run}
>
start
</Button>
</Flex.Item>
<Flex.Item span={12}>
<Button color="danger" size="small" block onClick={cancel}>
stop
</Button>
</Flex.Item>
</Flex>
</DemoContent>
);
};
network/useRequest/polling/index
<template>
<block>
<demo-content title="轮询">
<view>Username: {{ request.loading ? 'Loading...' : request.data }}</view>
<nut-row justify="space-between">
<nut-col :span="11">
<nut-button
:loading="request.loading"
size="small"
type="primary"
shape="square"
block
@click="request.run()"
>
run
</nut-button>
</nut-col>
<nut-col :span="11">
<nut-button
:loading="request.loading"
size="small"
type="danger"
shape="square"
block
@click="request.cancel()"
>
stop
</nut-button>
</nut-col>
</nut-row>
</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, {
pollingInterval: 1000,
pollingWhenHidden: false,
});
return { request };
},
};
</script>
API
Return
参数 | 说明 | 类型 |
---|---|---|
run | 启动轮询 | (...params: TParams) => void |
runAsync | 启动轮询 | (...params: TParams) => Promise<TData> |
cancel | 停止轮询 | () => void |
Options
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
pollingInterval | 轮询间隔,单位为毫秒。如果值大于 0,则启动轮询模式。 | number | 0 |
pollingWhenHidden | 在页面隐藏时,是否继续轮询。如果设置为 false,在页面隐藏时会暂时停止轮询,页面重新显示时继续上次轮询。 | boolean | true |
备注
options.pollingInterval
、options.pollingWhenHidden
支持动态变化。- 如果设置
options.manual = true
,则初始化不会启动轮询,需要通过run/runAsync
触发开始。 - 轮询原理是在每次请求完成后,等待
pollingInterval
时间,发起下一次请求。