React Query 与 Redux 协同设计 Coordinating React Query with Redux

📌 背景 / Background

Redux 用于集中式状态管理,而 React Query 管理异步数据及缓存。如何让它们协调:Redux 管状态意图,React Query 管异步数据,是构建复杂应用的关键技巧。

Redux is used for centralized state, while React Query manages asynchronous data and caching. Harmonizing them — letting Redux handle user intent and React Query handle data lifecycles — is a crucial technique for scalable apps.

🧩 技术目标 / Goals

    • Redux 存储分页参数如 page, limit
      Store pagination parameters like page, limit in Redux

    • React Query 根据 Redux 状态发起异步请求
      Let React Query trigger queries based on Redux state

    • 避免重复状态管理,职责清晰
      Avoid redundant state management, clearly separate responsibilities

⚙️ 代码实现 / Code Implementation

// movieSlice.ts
const movieSlice = createSlice({
  name: 'movie', // 用来生成action命名;并非store.getState().movie
  initialState: { page: 1, limit: 10 },
  reducers: {
    changePage(state, action) {
      state.page = action.payload
    }
  }
})
// Movies.tsx
const dispatch = useDispatch()
const { page, limit } = useSelector(state => state.movie) // consolg.log(store.getState())来确认

const { data } = useQuery({
  queryKey: ['MOVIES', page],
  queryFn: () => getMovies(page, limit),
  keepPreviousData: true
})

const pageChange = (p) => {
  dispatch(changePage(p))
}

✅ 状态职责划分 / State Responsibility Table

状态 / State存储位置 / Stored in说明 / Notes
page, limit Redux 用户意图,如翻页
分页数据 / Page data React Query 远程 API 缓存,响应式拉取
isLoading, error React Query 自动状态跟踪
搜索过滤条件 / Filters Redux UI 控制逻辑

❌ 错误做法 / Common Anti-patterns

    • ❌ 将 React Query 的数据同步写入 Redux
      Don't copy query results into Redux

    • ❌ 用 useState 再管理一份 page
      Avoid managing page separately via useState

    • ❌ 在 useEffect 中 dispatch Redux,只因数据变化
      Don't artificially sync query state into Redux with effects

✅ 推荐做法 / Recommended Pattern

  • Redux 只存元信息:页码、筛选、排序

  • React Query 管理远程数据内容和状态生命周期

  • 两者协同时,使用 queryKey 绑定 Redux 状态

📌 总结 / Summary

Redux 管「意图」——用户做了什么;React Query 管「响应」——从哪里拿数据,何时更新。通过解耦状态来源与数据生命周期,应用逻辑更清晰、可维护性更高。

Redux represents what the user wants, React Query manages how the app responds. This separation enhances clarity and maintainability in your app’s data layer.

 

posted @ 2025-06-06 02:09  PEAR2020  阅读(13)  评论(0)    收藏  举报