首页 > 解决方案 > 使用参数调用操作

问题描述

我正在使用 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 时如何传递参数。

标签: javascriptreactjsreduxrxjs

解决方案


我找到了答案:

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))
    )
)

推荐阅读