javascript - 使用参数调用操作
问题描述
我正在使用 React + Redux + Rxjs + typesafe-actions
+ TS,我想用参数调用动作。我现在的代码:
行动:
import { createAsyncAction } from 'typesafe-actions';
import {ICats} from '/api/cats';
export const FETCH_CATS_REQUEST = 'cats/FETCH_CATS_REQUEST';
export const FETCH_CATS_SUCCESS = 'cats/FETCH_CATS_SUCCESS';
export const FETCH_CATS_ERROR = 'cats/FETCH_CATS_ERROR';
export const fetchCats = createAsyncAction(
FETCH_CATS_REQUEST,
FETCH_CATS_SUCCESS,
FETCH_CATS_ERROR
) <void, ICats, Error> ();
呼叫调度:
store.dispatch(fetchCats.request());
我的史诗:
const fetchCatsFlow: Epic<Types.RootAction, Types.RootAction, Types.RootState> = (action$) =>
action$.pipe(
filter(isActionOf(fetchCats.request)),
switchMap(() =>
fromPromise(Cats.getDataFromAPI()).pipe(
map(fetchCats.success),
catchError(pipe(fetchCats.failure, of))
)
)
);
接口:
export const Cats = {
getDataFromAPI: () => $http.get('/cats').then(res => {
return res.data as any;
}),
};
它正在工作 - 调用 API 但没有参数。我尝试了很多次,但仍然不知道在调用 dispatch 时如何传递参数。
解决方案
我找到了答案:
export const fetchCats = createAsyncAction(
FETCH_CATS_REQUEST,
FETCH_CATS_SUCCESS,
FETCH_CATS_ERROR
) <void, ICats, Error> ();
变成:
type ICatsRequest = {
catType: string;
};
export const fetchCats = createAsyncAction(
FETCH_CATS_REQUEST,
FETCH_CATS_SUCCESS,
FETCH_CATS_ERROR
) <ICatsRequest, ICats, Error> ();
然后它允许我将指定的类型传递给调度:
store.dispatch(fetchCats.request({catType: 'XXX'}));
我还需要修改这个:
export const Cats = {
getDataFromAPI: (params) => $http.get('/cats', {
params: {
type: params.payload.catType
}
}).then(res => {
return res.data as any;
}),
};
和
switchMap((params) =>
fromPromise(Cats.getDataFromAPI(params)).pipe(
map(fetchCats.success),
catchError(pipe(fetchCats.failure, of))
)
)
推荐阅读
- angular - jasmine.clock().mockDate(...) 不适用于 Angular E2E 测试
- c# - Unity 在函数中放置 if 语句
- html - 如何使用 ngClass 在 Angular 中创建幻灯片?
- ruby-on-rails - 如何自动销毁accepted_nested_attributes_for的关联
- python-3.x - Python3.7.2如何对数字进行四舍五入
- react-native - react-native-scrollable-tab-view 不在 scrollView 标签中滚动
- python - Django 2.1 模板 img src 不工作
- java - 何时(多久)打开/关闭输入/输出流?
- c++ - Qmatrix4x4 翻译不生效
- javascript - 将选项值设置为选项 Class/ID jQuery