节流
通过设置 options.throttleWait
,进入节流模式,此时如果频繁触发 run
或者 runAsync
,则会以节流策略进行请求。
const { data, run } = useRequest(getUsername, {
throttleWait: 300,
manual: true,
});
如上示例代码,频繁触发 run
,只会每隔 300ms 执行一次。
你可以在下面 input 框中快速输入文本,体验效果
- React
- Vue
network/useRequest/throttle/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Cell, Field, Input } from '@taroify/core';
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';
async function getEmail(search?: string): Promise<string[]> {
console.log('throttle getEmail', search);
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock({ 'data|5': ['@email()'] }).data);
}, 300);
});
}
export default () => {
const { data, loading, run } = useRequest(getEmail, {
throttleWait: 1000,
manual: true,
});
return (
<DemoContent title="节流">
<Field align="center">
<Input
placeholder="Search Emails"
onChange={(event) => run(event.detail.value)}
/>
</Field>
{loading ? (
<Field>loading...</Field>
) : (
<>
{data?.map?.((v) => (
<Cell key={v}>{v}</Cell>
))}
</>
)}
</DemoContent>
);
};
network/useRequest/throttle/index
<template>
<block>
<demo-content title="节流">
<nut-row>
<nut-input
placeholder="Search Emails"
@update:model-value="request.run($event)"
/>
</nut-row>
<view v-if="request.loading">Loading...</view>
<template v-else>
<view v-for="item in request.data" :key="item">{{ item }}</view>
</template>
</demo-content>
</block>
</template>
<script>
import { useRequest } from 'taro-hooks';
import Mock from 'mockjs';
async function getEmail(search) {
console.log('throttle getEmail', search);
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock({ 'data|5': ['@email()'] }).data);
}, 300);
});
}
export default {
setup() {
const request = useRequest(getEmail, {
throttleWait: 1000,
manual: true,
});
return { request };
},
};
</script>
API
Options
throttle 所有参数用法和效果同 lodash.throttle
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
throttleWait | 节流等待时间, 单位为毫秒,设置后,进入节流模式 | number | - |
throttleLeading | 在节流开始前执行调用 | boolean | true |
throttleTrailing | 在节流结束后执行调用 | boolean | true |
备注
options.throttleWait
、options.throttleLeading
、options.throttleTrailing
支持动态变化。runAsync
在真正执行时,会返回Promise
。在未被执行时,不会有任何返回。cancel
可以中止正在等待执行的函数。