【问题标题】:React : Need a faster way to filter data and setStateReact:需要一种更快的方法来过滤数据和 setState
【发布时间】:2020-10-11 13:21:52
【问题描述】:

我需要为一个餐厅应用做一个菜单列表,菜单数据分为美式、中式、印度式、意大利式。我需要遍历所有这些以在 scrollspy 类型菜单中以某种方式呈现它。 为此,我将后端配置为一次发送所有项目,并且需要根据反应端的类别对其进行过滤和排序。

数据结构:

{
   _id: 5eef61450bd95e1f5c8f372f
   name: "Burger"
   category: "American"
   price: "100"
   isVeg: false
   __v: 0
}

我正在做的方式似乎太慢了,我相信有 必须成为一种更快/有效的方式。请建议,因为我的方式让我想呕吐。

const CheckForms = () => {
    const [american, setAmerican] = useState([]);
    const [italian, setItalian] = useState([]);
    const [indian, setIndian] = useState([]);
    const [chinese, setChinese] = useState([]);
    
    const fetchList = async () => {
        try {
            const res =  await axios.get(`http://localhost:5000/api/items`);
            const list =  res.data.response;  
            let ch = [];
            let ind = [];
            let am = [];
            let it = [];
            list.forEach(function(each){
                if (each.category === "Chinese") ch.push(each)
                else if (each.category === "Indian") ind.push(each)     
                else if (each.category === "American") am.push(each)     
                else if (each.category === "Italian") it.push(each)     
                else console.log('undefined category');
            });
            setAmerican(am);
            setIndian(ind);
            setChinese(ch);
            setItalian(it);
        } catch (err) {
            console.log(err.response);
        };
    };
    useEffect(()=> {
        fetchList();
    }, []);

    let render;
    if (indian.length > 0 && american.length > 0 && chinese.length > 0 && italian.length > 0) {
        render = (
            /*********************************
             *  AND FURTHER RENDERING LOGIC :( 
             ********************************/
        );
    };

【问题讨论】:

  • 迭代数组并过滤到“bins”或类别是一个O(n) 操作,你可以做的不多,使它更快。您是否只是“预感”它可以更快(或更高效),或者您对上面的代码有实际的性能问题?据我所知,这里唯一的“改进”在于可读性和/或代码维护(即,如果您需要添加/删除类别)。 @HMR 的解决方案具有更高的复杂性,O(n^2) 因为内部数组::concat,但允许使用 Map 自动处理此类别。

标签: javascript node.js reactjs react-redux react-router


【解决方案1】:

你可以试试 reduce:

const list = [
  { category: 'Chinese', name: 'one-1' },
  { category: 'Chinese', name: 'one-2' },
  { category: 'Indian', name: 'two' },
];
const groups = list.reduce(
  (result, item) =>
    result.set(
      item.category,
      (result.get(item.category) || []).concat(item)
    ),
  new Map()
);
console.log('Chinese',groups.get('Chinese'));
console.log('Indian',groups.get('Indian'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-13
    • 2019-12-07
    • 1970-01-01
    • 2023-01-19
    • 2017-12-12
    • 2013-09-28
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多