如何将 useReducer 和 rxjs 与 react hooks 一起使用?

How to use useReducer and rxjs with react hooks?

我想同时使用 react-hooks 和 rxjs 的 useReducer。 例如,我想从 API.

中获取数据

这是我为此编写的代码:

RXJS 钩子:

function useRx(createSink, data, defaultValue = null) {
    const [source, sinkSubscription] = useMemo(() => {
        const source = new Subject()
        const sink = createSink(source.pipe(distinctUntilChanged()));
        const sinkSubscription = sink.subscribe()
        return [source, sinkSubscription]
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    useEffect(() => {
        source.next(data)
    }, [source, data])

    useEffect(() => {
        return () => {
            sinkSubscription.unsubscribe()
        };
    }, [sinkSubscription])
}

减速器代码:

const dataFetchReducer = (state, action) => {
    switch (action.type) {
        case 'FETCH_LOADING':
            return {
                ...state,
                loading: true
            };
        case 'FETCH_SUCCESS':
            return {
                ...state,
                loading: false,
                total: action.payload.total,
                data: action.payload.data
            };
        case 'FETCH_FAILURE':
            return {
                ...state,
                error: action.payload
            };
        case 'PAGE':
            return {
                ...state,
                page: action.page,
                rowsPerPage: action.rowsPerPage
            };
        default:
            throw new Error();
    }
};

我是如何混合它们的:

function usePaginationReducerEndpoint(callbackService) {
    const defaultPagination = {
        statuses: null,
        page: 0,
        rowsPerPage: 10,
        data: [],
        total: 0,
        error: null,
        loading: false
    }
    const [pagination, dispatch] = useReducer(dataFetchReducer, defaultPagination)
    const memoPagination = useMemo(
        () => ({
            statuses: pagination.statuses,
            page: pagination.page,
            rowsPerPage: pagination.rowsPerPage
        }),
        [pagination.statuses, pagination.page, pagination.rowsPerPage]
    );
    useRx(
        memoPagination$ =>
        memoPagination$.pipe(
                map(memoPagination => {
                    dispatch({type: "FETCH_LOADING"})
                    return memoPagination
                }),
                switchMap(memoPagination => callbackService(memoPagination.statuses, memoPagination.page, memoPagination.rowsPerPage).pipe(
                    map(dataPagination => {
                        dispatch({ type: "FETCH_SUCCESS", payload: dataPagination })
                        return dataPagination
                    }),
                    catchError(error => {
                        dispatch({ type: "FETCH_SUCCESS", payload: "error" })
                        return of(error)
                    })
                ))
            ),
            memoPagination,
        defaultPagination,
        2000
    );
    function handleRowsPerPageChange(event) {
        const newTotalPages = Math.trunc(pagination.total / event.target.value)
        const newPage = Math.min(pagination.page, newTotalPages)
        dispatch({
            type: "PAGE",
            page: newPage,
            rowsPerPage: event.target.value
        });
    }
    function handlePageChange(event, page) {
        dispatch({
            type: "PAGE",
            page: page,
            rowsPerPage: pagination.rowsPerPage
        });
    }
    return [pagination, handlePageChange, handleRowsPerPageChange]
}

代码有效,但我想知道这是否是运气...

我知道这个资源:https://www.robinwieruch.de/react-hooks-fetch-data/。但我想混合使用 hooks 和 RXJS 的强大功能,以便在异步请求中使用例如带有 rxjs 的去抖功能...

感谢您的帮助,

您只需要一个 中间件 来连接 useReducer 和 rxjs,而不是自己创建一个。 使用 useReducer 会产生很多潜在的难以调试的代码,并且还需要一个独立的容器组件来放置 useReducer 以防止意外的全局重新渲染。

所以我建议使用 redux 放置 useReducer 从组件创建全局状态并使用 redux-observable(Redux 的基于 RxJS 6 的中间件)作为连接的中间件rxjs 和 redux.

如果你熟悉rxjs,使用起来会非常简单,如官网所示,从api获取数据将是: https://redux-observable.js.org/docs/basics/Epics.html

// epic
const fetchUserEpic = action$ => action$.pipe(
  ofType(FETCH_USER),
  mergeMap(action =>
    ajax.getJSON(`https://api.github.com/users/${action.payload}`).pipe(
      map(response => fetchUserFulfilled(response))
    )
  )
);