如何在Redux Thunk的payload创建器中使用TypeScript跳过第一个参数?

huangapple go评论77阅读模式
英文:

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&lt;
  // 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
    }
  }
&gt;(&#39;users/fetchById&#39;, async (userId, thunkApi) =&gt; {
  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&lt;
  // 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
    }
  }
&gt;(&#39;users/fetchById&#39;, async (_, thunkApi) =&gt; { // 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
})

huangapple
  • 本文由 发表于 2023年1月9日 02:19:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定