英文:
How can I skip first argument to the payload creator of Redux Thunk using typescript
问题
const fetchUserById = createAsyncThunk<
  // 返回的负载创建器的返回类型
  MyData,
  // 负载创建器的第一个参数
  number,
  {
    // 用于定义thunkApi字段类型的可选字段
    dispatch: AppDispatch
    state: State
    extra: {
      jwt: string
    }
  }
>('users/fetchById', async (userId, thunkApi) => {
  const response = await fetch(`https://reqres.in/api/users/${userId}`, {
    headers: {
      Authorization: `Bearer ${thunkApi.extra.jwt}`,
    },
  })
  return (await response.json()) as MyData
})
英文:
const fetchUserById = createAsyncThunk<
  // Return type of the payload creator
  MyData,
  // First argument to the payload creator
  number,
  {
    // Optional fields for defining thunkApi field types
    dispatch: AppDispatch
    state: State
    extra: {
      jwt: string
    }
  }
>('users/fetchById', async (userId, thunkApi) => {
  const response = await fetch(`https://reqres.in/api/users/${userId}`, {
    headers: {
      Authorization: `Bearer ${thunkApi.extra.jwt}`,
    },
  })
  return (await response.json()) as MyData
})
This snippet is from redux-tooklit documentation.
Here I am going to use get request, so I won't have arguments passed. How can I skip the first argument to the payload creator userId
答案1
得分: 1
为了避免传递任何不必要的参数,我们可以简单地这样做:
const fetchUserById = createAsyncThunk<
  // 返回的数据类型
  MyData,
  // 负载创建器的第一个参数
  void, // 在这里传递void类型
  {
    // 用于定义thunkApi字段类型的可选字段
    dispatch: AppDispatch
    state: State
    extra: {
      jwt: string
    }
  }
>('users/fetchById', async (_, thunkApi) => { // 在这里传递下划线(_)
  const response = await fetch(`https://reqres.in/api/users/${userId}`, {
    headers: {
      Authorization: `Bearer ${thunkApi.extra.jwt}`,
    },
  })
  return (await response.json()) as MyData
})
请注意,这是您提供的代码的中文翻译。
英文:
so to avoid passing any unnecessary arguments we can simply just do it like this:
const fetchUserById = createAsyncThunk<
  // Return type of the payload creator
  MyData,
  // First argument to the payload creator
  void, // pass void type here
  {
    // Optional fields for defining thunkApi field types
    dispatch: AppDispatch
    state: State
    extra: {
      jwt: string
    }
  }
>('users/fetchById', async (_, thunkApi) => { // pass underscore(_) here
  const response = await fetch(`https://reqres.in/api/users/${userId}`, {
    headers: {
      Authorization: `Bearer ${thunkApi.extra.jwt}`,
    },
  })
  return (await response.json()) as MyData
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论