跳到主要内容

依赖刷新

useRequest 提供了一个 options.refreshDeps 参数,当它的值变化后,会重新触发请求。

import { useState } from '@tarojs/taro';
const [userId, setUserId] = useState('1');

const { data, run } = useRequest(() => getUserSchool(userId), {
refreshDeps: [userId],
});

上面的示例代码,useRequest 会在初始化和 userId 变化时,触发函数执行。

与下面代码实现功能完全一致

import { useState, useEffect } from '@tarojs/taro';
const [userId, setUserId] = useState('1');

const { data, refresh } = useRequest(() => getUserSchool(userId));

useEffect(() => {
refresh();
}, [userId]);

你可以通过下面示例来体验效果

network/useRequest/refreshDeps/index
import React from 'react';
import DemoContent from '@src/components/DemoContent';
import { Field, ActionSheet } from '@taroify/core';

import { useState } from '@taro-hooks/core';
import { useRequest } from 'taro-hooks';

const userSchool = (id: string) => {
switch (id) {
case '1':
return 'Tsinghua University';
case '2':
return 'Beijing University';
case '3':
return 'Zhejiang University';
default:
return '';
}
};

async function getUserSchool(userId: string): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => {
resolve(userSchool(userId));
}, 1000);
});
}

export default () => {
const [userId, setUserId] = useState('1');
const [open, setOpen] = useState(false);
const { data, loading } = useRequest(() => getUserSchool(userId), {
refreshDeps: [userId],
});

return (
<DemoContent title="依赖刷新">
<Field align="center" onClick={() => setOpen(true)}>
{userId} (click here)
</Field>
<Field align="start">School: {loading ? 'Loading' : data}</Field>
<ActionSheet
open={open}
onSelect={(event) => {
setUserId(event.value);
setOpen(false);
}}
onClose={setOpen}
>
<ActionSheet.Action value="1" name="user 1" />
<ActionSheet.Action value="2" name="user 2" />
<ActionSheet.Action value="3" name="user 3" />
</ActionSheet>
</DemoContent>
);
};

API

Options

参数说明类型默认值
refreshDeps依赖数组,当数组内容变化后,发起请求。同 useEffect 的第二个参数。any[][]