如何在 "pending" 状态下通过 `createAsyncThunk` 发送自定义参数?

How I send custom parameters on `createAsyncThunk` on "pending" status?

创建 fetchUserById() 时定义其输出响应。

const fetchUserById = createAsyncThunk<{user: UserInterface, id: number}, number>(
  'users/fetchByIdStatus',
  async (userId) => {
    const response = await userAPI.fetchById(userId)
    return {user: response.data, id: userId}
  }
);

const userSlice = createSlice({
  name: "users",
  initialState: [],
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchUserById.pending, (state, { payload }) => {
      // how I configured custom value for this payload?
      // I need to send the user id.
    });
    builder.addCase(fetchUserById.fulfilled, (state, {payload}) => {
      /**
       * @var {UserInterface} user
       * @var {number} id;
       */
      const {id, user} = payload;
      state[id].loading = false;
      state[id].user = user;
    });
  },
});

但是当操作处于“待定”状态时,我如何定义响应?

您传递给 createAsyncThunk 的参数将在 action.meta.arg 中可用。所以在你的例子中,你可以这样引用:

builder.addCase(fetchUserById.pending, (state, { meta }) => {
      console.log(meta.arg); // meta.arg will have whatever value was passed as `userId`
    });