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

时间:2019-06-08 17:35:17

标签: rxjs 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]
}

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

  • 如果我在RXJS管道内调度可以吗?有什么风险?
  • 如果没有,如何将useReducer和RXJS混合使用?
  • 如果不是好的方法,那么好的方法是什么?

我知道这个资源:https://www.robinwieruch.de/react-hooks-fetch-data/。但是我想混合使用hook和RXJS的功能,以便在异步请求中将反跳功能与rxjs一起使用...

感谢您的帮助,

1 个答案:

答案 0 :(得分:0)

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

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

如果您非常了解rxjs,它将非常易于使用,如官方网络所示,从api提取数据将是: https://redux-observable.js.org/docs/basics/Epics.html

ruby-*