0

如何配置钩子,使其在从网络或缓存中获取新数据时不会返回上一个查询中的数据?
类似参数的东西keepPreviousData: false

如果您动态更改钩子的变量或查询,useQuery()则在获取新数据时,结果仍将包含以前的数据。虽然它对于无限滚动模式非常有用,但对于像搜索界面那样动态变化的查询来说它就不太有用了。在这样的界面中,用户不希望看到不再符合他的搜索查询的弃用结果。

样品:

const [search, setSearch] = useState('');

// The hook will fetch data matching the search variable typed by the user
const [result] = useQuery({
  query: "...",
  variables: {search}
});

// If the search variable changes,
// result still contains data from last query
//  while fetching new search
const data = result.data;


return (
  // user types and changes the search variable
  <TextInput onChangeText={setSearch} />
);

PS:如果它不存在,我也会奖励为此类功能进行 PR 的人。

4

1 回答 1

0

根据文档useQuery

结果是一个形状为 an 的对象,OperationResult并添加了一个fetching: boolean属性,指示是否正在获取查询。

因此,检查是否result.fetching为真就足够了:

function SearchForm() {
    const [search, setSearch] = useState('');

    // The hook will fetch data matching the search variable typed by the user
    const [result] = useQuery({
        query: "...",
        variables: { search }
    });

    const data = result.data;

    return <>
        <TextInput onChangeText={setSearch} />
        {
            !result.fetching && result.data
            ? <SearchResults data={result.data} />
            : null
        }
    </>;
}
于 2021-11-25T11:28:19.647 回答