hooks useRequest 预请求

8wigbo56  于 2022-10-25  发布在  其他
关注(0)|答案(6)|浏览(194)

假设有一个书籍列表页,点击书名就会进入到书籍的详情页。我想在列表页利用 cacheKey 做一个预加载,当鼠标移到具体书名的时候就发起请求,这样当用户真正点击进去发起请求时 cacheKey 与列表页请求的 cacheKey 相同。但以目前的方式想要实现我只能想到这样,是我错过了什么吗?

// services
const getBook = (id) => axios.get(`/book/${id}`).then((res) => res.data);
const getBookList = () => axios.get("/books").then((res) => res.data);

const Books = () => {
  const { data } = useRequest(getBookList);

  const [prerequestId, setPrerequestId] = useState(null);
  useRequest(getBook, {
    cacheKey: `book_${prerequestId}`,
    ready: !!prerequestId,
  });

  return (
    <ul>
      {data.map((book) => (
        <a
          onMouseEnter={() => setPrerequestId(book.id)}
          href={`/book/${book.id}`}
        >
          {book.name}
        </a>
      ))}
    </ul>
  );
};

const Book = () => {
  const { id } = useParams();
  const { data } = useRequest(() => getBook(id), {
    cacheKey: `book_${id}`,
  });
  return <div>{data.name}</div>;
};

如果有一个这样 API 我觉得会比较优雅?

import { prerequest } from 'ahooks'

const Books = () => {
  const { data } = useRequest(getBookList);

  const handleMouseEnter = (id) => {
    // 第一个参数是 service,第二个参数是 cacheKey
    prerequest(() => getBook(id), `book_${id}`)
  }

  return (
    <ul>
      {data.map((book) => (
        <a
          onMouseEnter={() => handleMouseEnter(book.id)}
          href={`/book/${book.id}`}
        >
          {book.name}
        </a>
      ))}
    </ul>
  );
};

参考: https://tanstack.com/query/v4/docs/guides/prefetching

ehxuflar

ehxuflar2#

这里有个问题是,想要做到这样的预请求只能通过重渲染触发 useRequestready 甚至 cacheKey 改变,但我理解“预请求”这个行为应该不需要触发重渲染,甚至不应该是一个 hooks?可能我下面的API有点误导我修改一下

5sxhfpxr

5sxhfpxr3#

@brickspert useRequest 的预加载好像没有内置是么,要通过 cacheKey 去做么

gwbalxhn

gwbalxhn4#

现在还不支持这种动态的 cacheKey,可以考虑支持一下。

idfiyjo8

idfiyjo86#

我尝试一下

@brickspert@hchlq@crazylxr 我有一个思路,现在不是有一个 cacheKey 的缓存功能吗?是不是可以利用这个功能实现预请求?在需要预请求的时候调用缓存功能,但是不返回结果,这个思路可以吗?

相关问题