用于数据获取的自定义钩子

时间:2020-07-09 15:14:03

标签: javascript reactjs react-router react-hooks antd

我已经制作了这个自定义钩子,以使用 fetcher 来获取数据,并返回包含数据的状态以显示在antd表中(喜欢它们)。 我不确定这是使用钩子的正确方法,我在我有疑问的代码中添加了注释。

import { useEffect, useReducer } from 'react';
import { useLocation, useHistory } from 'react-router-dom';
import queryString from 'query-string'

const initialState = { data: [], loading: true };

const fetchData = (fetcher, params, dispatch) => {

    //in this case i need to change my state to loading, the reducer will do the trick, but i fill this kinda triky, should i call the fatcher after the dispatch end using an effect?

    dispatch({ type: 'FETCHING' })
    fetcher({ ...params, page: params.page > 0 ? params.page - 1 : params.page }, response => dispatch({ type: 'DATA_RECEIVED', payload: response.data }));
    return () => {
        console.log('unmounting useGridDataFetch')
    };
}

const handlePageChange = (page, history, location) => {
    const qparams = queryString.parse(location.search)
    const qs = Object.keys(qparams).map(key => key != 'page' ? `&${key}=${qparams[key]}` : '')
    history.push(`${history.location.pathname}?page=${page}${qs.reduce((acc,val)=> acc + val , '')}`)
}


const useGridDataFetch = (fetcher, initialParams) => {
    const location = useLocation()
    const history = useHistory()
    const params = { ...initialParams, ...queryString.parse(location.search) }

    // to use history and location inside my reducer to change the querystring on page change, i had to put the reducer definition inside the body of the hook, is there a better way?

    const reducer = (state, action) => {
        switch (action.type) {
            case 'FETCHING':
                return { loading: true };
            case 'DATA_RECEIVED':
                const pagination = {
                    pageSize: action.payload.pageable.pageSize,
                    current: action.payload.pageable.pageNumber + 1,
                    total: action.payload.totalElements,
                    onChange: page => handlePageChange(page, history, location)
                }
                return { dataSource: action.payload.content, loading: false, pagination };
            default:
                throw new Error();
        }
    }

    const [state, dispatch] = useReducer(reducer, initialState);
    useEffect(() => fetchData(fetcher, params, dispatch), [location.search])

    return [state, (_params) => fetchData(fetcher, { ...params, ..._params }, dispatch)]
}


export default useGridDataFetch

总的来说,您可以给我的一些改进我的代码的技巧将不胜感激。

谢谢。

1 个答案:

答案 0 :(得分:1)

我会尽力帮助您

首先,您必须从钩子中提取减速器。 reducer函数应独立于钩子, 因为useReducer(reducer, initialState);仅使用这两个参数reducerinitialState一次,并且不会在下一次调用时对其进行更新。结果,您无法在化简器中使用handlePageChange方法。

第二点是减速器必须使用与{ data: Array, isLoading: Boolean }相同的接口返回数据。对于您的情况,您对reducer有3种不同的响应:init-{ data: Array, loading: Boolean }之后,FETCHING-{ loading: Boolean }之后和DATA_RECEIVED-{ dataSource: Object, loading: Boolean, pagination: Object }

我建议您不要使用useReducer。我将建议我实现您的代码

const useGridDataFetch = (fetcher, initialParams) => {
  const { data, isLoading } = useGetData(fetcher, initialParams);
  const { dataSource, pagination } = useGetPreparedData(data);
  
  return {
    isLoading,
    dataSource,
    pagination,
  }
}

const useGetData = (fetcher, initialParams) => {
  const [isLoading, setIsLoading] = useState(false);
  const [data, setData] = useState({});

  const location = useLocation();

  useEffect(() => {
    const params = {
      ...initialParams,
      ...queryString.parse(location.search)
    }
    setIsLoading(true);
    fetcher({
      ...params,
      page: params.page > 0 ? params.page - 1 : params.page
    }, response => {
      setData(response.data);
      setIsLoading(false);
    });
  }, [location.search]);

  return {
    isLoading,
    data
  }
}

const useGetPreparedData = (data) => {
  const location = useLocation();
  const history = useHistory();

  const handlePageChange = useCallback((page) => {
    const qparams = queryString.parse(location.search);
    const qs = Object.keys(qparams).map(key => key != 'page' ? `&${key}=${qparams[key]}` : '')
    history.push(`${location.pathname}?page=${page}${qs.reduce((acc,val)=> acc + val , '')}`)
  }, [location.pathname, location.search, history]);

  return useMemo(() => {
    if (!data.content) {
      return {
        dataSource: [],
        pagination: {}
      }
    }

    const pagination = {
      pageSize: data.pageable.pageSize,
      current: data.pageable.pageNumber + 1,
      total: data.totalElements,
      onChange: page => handlePageChange(page)
    }

    return {
      dataSource: data.content,
      pagination
    };
  }, [data, handlePageChange])
}

此代码可能会出现一些错误,但我认为主要思想很简单