在编程中,thunk 一词指的是执行延迟工作的代码部分,例如 JavaScript 中的异步函数。
Redux 存储本身不处理异步逻辑。它只知道如何:
但是等等,如果是这样的话,我们如何调用 API 并根据它们的响应更新状态,这通常需要时间?我们该如何处理?
这就是 thunk 函数的用武之地。
thunk 函数是为处理异步逻辑(例如调用 API)而创建的函数。它需要两个参数dispatch和getState来调度动作,并在需要时访问当前状态。
const getAllUsers = () => { return async (dispatch, getState) => { dispatch(fetingAllUsers()); try { const users = await getUsers(); dispatch(userUpdated(users)); } catch (err) { dispatch(logError(err)) } } }
返回的函数是 thunk 函数,getAllUsers 在本例中被称为 thunk 动作创建者,它将像这样调度:
dispatch(getAllUsers())
如果需要,可以使用 thunk 函数中使用的参数来调度 thunk 动作创建者。
Redux Toolkit 提供了 createAsyncThunk API 来轻松生成 thunk:
import { createAsyncThunk } from '@reduxjs/toolkit'; export const fetchUserById = createAsyncThunk( 'user/fetchUserById', async (userId) => { const user = await someHttpRequest(userId); return user; } );
fetchUserById 是这里创建的 thunk 函数。 createAsyncThunk 采用两个参数:
除了让您为 API 调用创建 thunk 函数之外,createAsyncThunk 还会自动调度操作来跟踪 API 请求的状态:
这真的很有用。例如,当状态处于挂起状态时,我们可以在 UI 中显示加载程序,并让用户知道正在发生某些事情。
现在我们已经创建了 fetchUserById thunk,我们可以使用 userSlice 中的 extraReducers 字段来处理状态状态更改:
import { createSlice } from '@reduxjs/toolkit'; const initialState = { user: null, status: 'idle', // 'idle' | 'pending' | 'succeeded' | 'failed' error: null, }; export const userSlice = createSlice({ name: 'user', initialState, reducers: { usernameUpdated: (state, action) => { state.user.username = action.payload; }, emailUpdated: (state, action) => { state.user.email = action.payload; }, userDataCleared: (state) => { state.user = null; state.status = 'idle'; }, }, extraReducers: (builder) => { builder .addCase(fetchUserById.pending, (state) => { state.status = 'pending'; }) .addCase(fetchUserById.fulfilled, (state, action) => { state.status = 'succeeded'; state.user = action.payload; }) .addCase(fetchUserById.rejected, (state, action) => { state.status = 'failed'; state.error = action.error.message || 'Something went wrong.'; }); }, }); export const { usernameUpdated, emailUpdated, userDataCleared } = userSlice.actions; // Selector for the status to use in the application's components export const selectStatus = (state) => state.user.status;
如果我们想在调用API之前检查一些条件怎么办?例如,如果状态已经处于待处理状态,我们不想调用它两次。在这种情况下,我们可以使用 createAsyncThunk 接受的第三个参数来写入条件。
const getAllUsers = () => { return async (dispatch, getState) => { dispatch(fetingAllUsers()); try { const users = await getUsers(); dispatch(userUpdated(users)); } catch (err) { dispatch(logError(err)) } } }
要了解如何将 Typescript 与 thunk 函数结合使用,请阅读类型检查 Redux Thunk。
以上是Redux 工具包:创建 Thunk 函数的详细内容。更多信息请关注PHP中文网其他相关文章!