react使用new Map完成多个if条件判断的优化

作者分享了工作中遇到的大量if-else条件判断代码,并寻求更简洁的解决方案,提出使用新Map进行代码重构,减少代码复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前在工作中遇到的代码,是之前的同事写的,写了差不多一百行if  else ,,,,

看的我真是头疼欲裂,今天下决心改一下,

但是感觉这样还是很鸡肋,不知道大家有没有什么更好的方案,烦请留言,switch case除外

 //原始代码,这里只是举个例子
        const depCode = cookie.load('depCode');
        //这里可能有很多判断条件
          if (depCode == '0001') {
            window.open('http://baidu.com');
        } else if (depCode == '0002' || depCode == '0003' || depCode == '9639' || depCode == '8465') {
            window.open('http://taobao.com');
        } else if (depCode == '0004' || depCode == '0005' || depCode == '00006' || depCode == '7458' || depCode == '1254') {
            window.open('http://jingdong.com');
        } else if (depCode == '0007') {
            window.open('http://youzheng.com');
        } else if (depCode == '0008') {
            window.open('http://csdn.com');
        } else {
            setModal(true);//antd Modal的显示
        }

        //使用new Map去完成条件判断,感觉这样还是很繁琐
        const optimization = (code, token, setModal) => {
            const depCodeArr1 = ['0001'];
            const depCodeArr2 = ['0002', '0003', '9639', '8465'];
            const depCodeArr3 = ['0004', '0005', '00006', '7458', '1254'];
            const depCodeArr4 = ['0007'];
            const depCodeArr5 = ['0008'];

            const mjMap = new Map()
                .set(deptCodeArr1.includes(code) ? code : '', 'http://baidu.com')
                .set(depCodeArr2.includes(code) ? code : '', 'http://taobao.com')
                .set(depCodeArr3.includes(code) ? code : '', 'http://jingdong.com')
                .set(depCodeArr4.includes(code) ? code : '', 'http://youzheng.com')
                .set(depCodeArr5.includes(code) ? code : '', 'http://csdn.com')
            const isMjMapCode = mjMap.get(code);
            return isMjMapCode && window.open(isMjMapCode) || setModal(true);
        }


<think>我们正在讨论在React应用中请求多个服务器的方法或最佳实践。根据引用[1]和引用[4],我们知道React应用通常使用状态管理来处理动态数据,并且推荐将数据获取和控制器逻辑分离到高阶组件中,保持视图简单。 在React中,处理多个服务器请求的常见方法包括: 1. 顺序请求:使用`async/await`按顺序发送请求。 2. 并行请求:使用`Promise.all()`或`Promise.allSettled()`同时发送多个请求。 3. 使用自定义Hook封装数据获取逻辑。 4. 使用状态管理库(如Redux)来管理多个请求的状态。 最佳实践建议: - 避免在组件渲染函数中直接发起请求,应在`useEffect`或事件处理函数中发起。 - 处理加载状态和错误状态。 - 考虑请求的依赖关系(并行或串行)。 - 使用AbortController取消请求以避免内存泄漏。 下面是一个使用`Promise.all`进行并行请求的示例: ```javascript import React, { useState, useEffect } from 'react'; function MultiRequestComponent() { const [data, setData] = useState({ user: null, posts: null }); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { // 使用Promise.all并行请求 const [userResponse, postsResponse] = await Promise.all([ fetch('https://api.example.com/user'), fetch('https://api.example.com/posts') ]); // 检查响应是否成功 if (!userResponse.ok || !postsResponse.ok) { throw new Error('One of the requests failed'); } const userData = await userResponse.json(); const postsData = await postsResponse.json(); setData({ user: userData, posts: postsData }); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchData(); }, []); // 空依赖数组表示只在组件挂载时执行 if (loading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; return ( <div> <h1>User: {data.user.name}</h1> <h2>Posts:</h2> <ul> {data.posts.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> </div> ); } export default MultiRequestComponent; ``` 在这个例子中,我们同时请求用户数据和帖子数据,并在两个请求都完成后更新状态。 如果请求之间有依赖关系(例如,需要先获取用户ID,再根据用户ID获取帖子),则可以使用串行请求: ```javascript useEffect(() => { const fetchData = async () => { try { const userResponse = await fetch('https://api.example.com/user'); if (!userResponse.ok) throw new Error('User request failed'); const userData = await userResponse.json(); const postsResponse = await fetch(`https://api.example.com/posts?userId=${userData.id}`); if (!postsResponse.ok) throw new Error('Posts request failed'); const postsData = await postsResponse.json(); setData({ user: userData, posts: postsData }); } catch (err) { setError(err.message); } finally { setLoading(false); } }; fetchData(); }, []); ``` 另外,为了更好的可维护性和可测试性,可以将数据获取逻辑提取到自定义Hook中,或者使用React Query这样的库来管理服务器状态。 引用[4]提到的高阶组件(HOC)模式,也可以用于抽象多个请求,但如今更推荐使用Hooks。 总结最佳实践: - 并行请求使用`Promise.all`或`Promise.allSettled`(当需要所有请求完成,即使有失败时)。 - 串行请求使用`async/await`链式调用。 - 使用AbortController取消请求(在组件卸载时取消未完成的请求)。 - 处理加载状态和错误状态。 - 将数据获取逻辑与UI分离(自定义Hook或状态管理)。 §§相关问题§§ 1.React中如何处理多个相互依赖的API请求? 2. 如何取消正在进行的多个请求? 3. React Query如何简化多个服务器请求的管理? 4.React中,如何优雅地处理多个请求的错误?</think>在 React 应用中高效处理多个服务器请求的最佳实践如下,结合了 React 特性与现代异步处理技术: ### 1. 并行请求优化 使用 `Promise.all()` 或 `Promise.allSettled()` 同时发起多个独立请求: ```javascript useEffect(() => { const fetchData = async () => { try { const [userData, productData] = await Promise.all([ fetch('/api/user'), fetch('/api/products') ]); // 处理数据... } catch (error) { // 统一错误处理 } }; fetchData(); }, []); ``` **优势**:减少总等待时间,避免"瀑布式"请求[^4] ### 2. 请求依赖管理 对相互依赖的请求使用 `async/await` 链式调用: ```javascript useEffect(() => { const fetchSequential = async () => { const user = await fetchUser(); const orders = await fetchOrders(user.id); // 依赖用户ID setData({ user, orders }); }; fetchSequential(); }, []); ``` ### 3. 自定义 Hook 封装 创建可复用的请求逻辑: ```javascript // useMultiFetch.js const useMultiFetch = (urls) => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const responses = await Promise.all(urls.map(url => fetch(url))); const jsonData = await Promise.all(responses.map(res => res.json())); setData(jsonData); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchData(); }, [urls]); return { data, loading, error }; }; // 组件中使用 const { data: [users, products], loading } = useMultiFetch(['/api/users', '/api/products']); ``` ### 4. 请求取消与清理 使用 AbortController 避免组件卸载后的状态更新: ```javascript useEffect(() => { const controller = new AbortController(); const fetchData = async () => { try { const response = await fetch('/api/data', { signal: controller.signal }); // 处理响应... } catch (err) { if (err.name !== 'AbortError') { // 处理真实错误 } } }; fetchData(); return () => controller.abort(); // 清理函数 }, []); ``` ### 5. 高级状态管理 对复杂场景使用状态管理库: ```jsx // 使用 Redux Toolkit 示例 import { createAsyncThunk } from '@reduxjs/toolkit'; export const fetchAllData = createAsyncThunk('data/fetchAll', async () => { const [res1, res2] = await Promise.all([ fetch('/api/source1'), fetch('/api/source2') ]); return { data1: await res1.json(), data2: await res2.json() }; }); // 组件中 dispatch(fetchAllData()).then(unwrapResult).then(data => { // 更新UI }); ``` ### 6. 错误处理增强 实现细粒度错误处理: ```javascript const handleErrors = (responses) => { return responses.map(res => { if (!res.ok) throw new Error(`${res.status} - ${res.url}`); return res.json(); }); }; // 在Promise.all中使用 Promise.all(fetchRequests.map(req => req.catch(e => e))) .then(handleErrors) .then(data => /* 处理数据 */) .catch(error => /* 全局错误处理 */); ``` ### 最佳实践总结 1. **并行优先**:独立请求使用 `Promise.all()` 最大化效率 2. **依赖管理**:链式调用处理请求依赖关系 3. **逻辑封装**:通过自定义 Hook 复用请求逻辑[^4] 4. **资源清理**:AbortController 防止内存泄漏 5. **状态分离**:复杂场景使用 Redux/Context 管理状态 6. **错误边界**:组件级错误边界捕获渲染错误 7. **加载状态**:提供 skeleton screens 等加载反馈 这些实践能显著提升应用性能,同时保持代码可维护性,特别适合电商购物车、仪表盘等多数据源场景[^1]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值