React:需要一种更快的方法来过滤数据和setState

时间:2020-06-21 16:46:30

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

我需要为餐厅应用创建菜单列表,并且菜单数据按美国,中国,印度,意大利分类。我需要遍历所有这些内容以某种方式在scrollspy类型菜单中呈现它。 为此,我已将后端配置为立即发送所有ITEMS ,并且需要根据反应侧的类别对其进行过滤和排序。

数据结构:

{
   _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 :( 
             ********************************/
        );
    };

1 个答案:

答案 0 :(得分:0)

您可以尝试减少:

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'));