具有 React 查询的 CRA React 项目的项目结构

Neh*_*nia 4 reactjs react-query

我们正在使用 CRA 开始一个新的 React 项目。并且,计划使用 React Query。

需要有关项目文件夹结构的帮助。基于功能的文件夹结构与基于文件类型的结构相比有何优势?

另外,仅使用 axios/fetch 调用并直接在组件中创建 useQuery/useMutation 挂钩的服务/API 有什么优势?与为每个reactQuery 创建自定义 Hook 相比?

// API call in a service file and using that API call in the component
export const fetchPost = (key, postId) =>
  axios.get(`/api/posts/${postId}`).then((res) => res.data)

//Custom Hooks for each API call in a service 
export default function usePost(postId) {
  return useQuery(postId && ['post', postId], fetchPost)
}
Run Code Online (Sandbox Code Playgroud)

TkD*_*odo 10

基于功能的文件夹结构与基于文件类型的结构相比有何优势?

我完全喜欢基于功能的文件夹。它们会将属于您的功能的代码放在功能目录中,并更容易推断出特定事物(尤其是查询)的使用位置。大多数查询仅“属于”一个功能 - 如果您需要在多个功能中进行查询,您仍然可以将其上移到顶级queries目录。但是只有queries,utilscomponentsas 目录使得很难看出什么在哪里使用。

我可以推荐这篇文章: https: //kentcdodds.com/blog/colocation

关于自定义挂钩:创建自定义挂钩几乎总是好的。我将实际的获取函数保留在查询函数旁边,但不导出。就像是:

in: 
features
  - posts
    - queries.ts

const fetchPost = () => ...

export const usePost = (id) => useQuery(...)
Run Code Online (Sandbox Code Playgroud)

有了这个:

  • 您可以将实际数据提取保留在 ui 之外,但与 useQuery 调用位于同一位置。
  • 您可以将一个查询键(以及可能的类型定义)的所有用法保留在一个文件中。
  • 如果您需要调整一些设置或添加一些数据转换,您可以在一处完成。