我正在使用React + Redux + Rxjs + typesafe-actions
+ TS,我想使用params调用action。我现在的代码:
动作:
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))
)
)
);
API:
export const Cats = {
getDataFromAPI: () => $http.get('/cats').then(res => {
return res.data as any;
}),
};
而且有效-调用API但没有参数。我尝试了很多次,但仍然不知道在调用dispatch时如何传递参数。
答案 0 :(得分:2)
我找到了答案:
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))
)
)