关于中间件 thunk 额外参数的问题
来源:9-7 【中间件】使用redux-thunk中间价实现异步action

粉墨登场
2022-02-08
老师您好,中间件 thunk 的类型定义 ThunkAction<R, S, E, A> 中第三个泛型 E 表示中间件的额外参数,但是这个参数是从哪里来呢?按照我的理解,在分发中间件时如果要传递额外的参数应该是在外层函数的入参中获取。像这样,下面放了一段示例代码。
// 中间件函数
export const getRecommendProducts_thunk = (
// 这里获取额外的参数
params: string,
......
): ThunkAction<R, S, E, A> => {
return (dispatch, getState) => {
// 这里执行中间件函数操作
};
};
// UI 中使用
componentDidMount () {
// 这里调用中间件函数,传递额外的参数。
dispatch(getRecommendProducts_thunk('extraArgument'));
};
写回答
1回答
-
阿莱克斯刘
2022-02-25
同学你好,从redux官网,我们可以看到thunkAction是这样定义的
这里的E则代表额外参数extra argument
如果我给你这样一个例子,你应该就能明白了?
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 })
00
相似问题