是否可以在 createAsyncthunk 中手动分派 thunk 状态

Is it possible to manually dispatch thunk state in createAsyncthunk

各位程序员,

最近学习react-redux很开心,但我确实有一个问题困扰着我。

我的理解是,使用createAsyncThunk会自动生成动作类型常量。 (待处理、已完成和已拒绝)

我想知道的是,有什么方法可以在 createAsyncthunk 期间手动调度操作类型,以便我们的代码具有更大的灵活性。

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'

// First, create the thunk
const fetchUserById = createAsyncThunk(
  'users/fetchByIdStatus',
  async (userId, thunkAPI) => {
    const response = await userAPI.fetchById(userId).then(
       ...
       dispatch(fulfilled)   // is this possible ?
    ).catch(
       dispatch(rejected)    // is this possible ?
    )

    return response.data
  }
)

// Then, handle actions in your reducers:
const usersSlice = createSlice({
  name: 'users',
  ...,
  extraReducers: {
    // Add reducers for additional action types here, and handle loading state as needed
    [fetchUserById.fulfilled]: (state, action) => {
      // Add user to the state array
      state.entities.push(action.payload)
    }
  }
})

// Later, dispatch the thunk as needed in the app
dispatch(fetchUserById(123))

createAsyncThunk 的要点是它会生成这些操作类型,_并自动为您分派它们。你肯定不需要自己dispatch(fulfilled()),因为那是createAsyncThunk为你做的——你只需要return一个解决或解决的承诺拒绝,它会根据此分派 fulfilled/rejected 操作类型。

可以访问 thunkAPI.dispatch,因此您可以在必要时分派其他操作,但您无需担心 fulfilled/rejected自己行动。