Loading Delay
通过设置 options.loadingDelay
,可以延迟 loading
变成 true
的时间,有效防止闪烁。
- React
- Vue
const { loading, data } = useRequest(getUsername, {
loadingDelay: 300,
});
return <div>{loading ? 'Loading...' : data}</div>;
<template>
<block>
<view>{{request.loading ? 'Loading...' : request.data}}</view>
</block>
</template>
<script>
export default {
setup() {
// 由于要保证request内部的变量不失活。 这里简单的可以将request直接抛出
const request = useRequest(getUsername, {
loadingDelay: 300,
});
return {
request,
};
},
};
</script>
例如上面的场景,假如 getUsername
在 300ms 内返回,则 loading
不会变成 true
,避免了页面展示 Loading...
的情况。
你可以快速点击下面示例中的按钮以体验效果
- React
- Vue
network/useRequest/loadingDelay/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Button, 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()'));
}, 200);
});
}
export default () => {
const action = useRequest(getUsername);
const withLoadingDelayAction = useRequest(getUsername, {
loadingDelay: 300,
});
const trigger = () => {
action.run();
withLoadingDelayAction.run();
};
return (
<DemoContent title="loading Delay">
<Field align="center">
<Button
loading={withLoadingDelayAction.loading}
color="primary"
size="small"
block
onClick={trigger}
>
run
</Button>
</Field>
<Field align="start">
Username: {action.loading ? 'Loading...' : action.data}
</Field>
<Field align="start">
Username:{' '}
{withLoadingDelayAction.loading
? 'Loading...'
: withLoadingDelayAction.data}
</Field>
</DemoContent>
);
};
network/useRequest/loadingDelay/index
<template>
<block>
<demo-content title="loading Delay">
<nut-button
:loading="withLoadingDelayAction.loading"
size="small"
type="primary"
shape="square"
block
@click="trigger()"
>
run
</nut-button>
<view>Username: {{ action.loading ? 'Loading...' : action.data }}</view>
<view
>Username:
{{
withLoadingDelayAction.loading
? 'Loading...'
: withLoadingDelayAction.data
}}</view
>
</demo-content>
</block>
</template>
<script>
import { useRequest } from 'taro-hooks';
import { escapeState } from '@taro-hooks/shared';
import Mock from 'mockjs';
function getUsername() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Mock.mock('@name()'));
}, 200);
});
}
export default {
setup() {
const action = useRequest(getUsername);
const withLoadingDelayAction = useRequest(getUsername, {
loadingDelay: 300,
});
const trigger = () => {
escapeState(action).run();
escapeState(withLoadingDelayAction).run();
};
return { action, withLoadingDelayAction, trigger };
},
};
</script>
API
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
loadingDelay | 设置 loading 变成 true 的延迟时间 | number | 0 |
备注
options.loadingDelay
支持动态变化。