跳到主要内容

Loading Delay

通过设置 options.loadingDelay ,可以延迟 loading 变成 true 的时间,有效防止闪烁。

const { loading, data } = useRequest(getUsername, {
loadingDelay: 300,
});

return <div>{loading ? 'Loading...' : data}</div>;

例如上面的场景,假如 getUsername 在 300ms 内返回,则 loading 不会变成 true,避免了页面展示 Loading... 的情况。

你可以快速点击下面示例中的按钮以体验效果

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>
);
};

API

参数说明类型默认值
loadingDelay设置 loading 变成 true 的延迟时间number0

备注

options.loadingDelay 支持动态变化。