用于异步工作的 redux 中间件是否比执行 http 请求的自定义钩子更好

问题描述 投票:0回答:2

我想知道哪种方法在哪种情况下更好:

  1. React 针对 http 请求的自定义钩子,我们在其中放置加载、错误和数据的状态,然后在功能组件内我们只需使用该钩子获取数据,然后将其渲染到 ui 和/或将其保存到 redux。

    例如:

    const useFetch = (query) => {
        const [status, setStatus] = useState('idle');
        const [data, setData] = useState([]);
    
        useEffect(() => {
            if (!query) return;
    
            const fetchData = async () => {
                setStatus('fetching');
                const response = await fetch(
                    `https://hn.algolia.com/api/v1/search?query=${query}`
                );
                const data = await response.json();
                setData(data.hits);
                setStatus('fetched');
            };
    
            fetchData();
        }, [query]);
    
        return { status, data };
    };
    
  2. 或者我们应该使用 redux 或 redux 工具包的中间件来执行 http 或任何异步工作,然后在该中间件中分派一个操作来更新 redux 存储。

    例如:

javascript reactjs redux redux-toolkit react-custom-hooks
2个回答
0
投票

不完全是一个堆栈溢出问题,因为这是一个意见......

但是,由于还不到 2022 年,我 100% 会选择 RTKQ,https://redux-toolkit.js.org/rtk-query/overview

好处(小清单):

  • 缓存
  • 额外减速器
  • 转换响应
  • 从结果中选择
  • 自动失效、重新获取、轮询
  • 您仍然可以使用 axios 或 gql

您不必自己编写所有逻辑......


0
投票

这绝对是一个意见类型的问题,所以对我的回答持保留态度。但你应该看看 React Query。您仍然可以为您的 redux 存储使用减速器,只需使用 React Query 而不是额外的减速器。

https://react-query-v3.tanstack.com/

© www.soinside.com 2019 - 2024. All rights reserved.