在单独的文件中使用自定义操作的 CreateAsyncThunk

问题描述 投票:0回答:1

也许这是反模式,但我仍然想看看这是否可能

使用

createAsyncThunk
(例如
fetchDataThunk
)时,您将获得 3 个操作
fetchDataThunk.pending
fetchDataThunk.fulfilled
fetchDataThunk.rejected

有没有办法将操作放在单独的文件中并将它们作为参数传递给 thunk ?我想避免在我的减速器上完全导入我的 thunk 文件。

reactjs redux react-redux redux-thunk thunk
1个回答
0
投票

是的,这是可能的。您需要做的就是在单独的文件中创建操作处理函数,然后从

createAsyncThunk
函数调用它们。

这是您的

Actions.ts
文件:

export const fetchUsersPending = () => ({ type: 'FETCH_USERS_PENDING' } as const)
export const fetchUsersFulfilled = (data: any) => ({ type: 'FETCH_USERS_FULFILLED', payload: data } as const)
export const fetchUsersRejected = (error: string) => ({ type: 'FETCH_USERS_REJECTED', payload: error } as const)

然后是你的

Thunk.ts
文件:

import { fetchUsersPending, fetchUsersFulfilled, fetchUsersRejected } from "./Actions.ts"

export const fetchUsersThunk = createAsyncThunk(
  'fetchUsers',
  async (params: any, { dispatch }) => {
    try {
      dispatch(fetchUsersPending())
      const response = await fetchRequestFunction(params)
      dispatch(fetchUsersFulfilled(response.data))
      return response.data
    } catch (error) {
      dispatch(fetchUsersRejected(error.message))
      throw error
    }
  }
)
© www.soinside.com 2019 - 2024. All rights reserved.