3

何时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;
    });
  },
});

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

4

1 回答 1

5

您传入的 argcreateAsyncThunk将在action.meta.arg. 因此,在您的示例中,您可以这样引用:

builder.addCase(fetchUserById.pending, (state, { meta }) => {
      console.log(meta.arg); // meta.arg will have whatever value was passed as `userId`
    });
于 2020-07-24T17:52:25.823 回答