目录
- 原始代码
- 如何优化
- 1. 函数式简洁风格
- 2. hook 封装(重点)
- 3. 性能优化
原始代码
const GoodList = ({ goods }) => {if (goods.length === 0) {return <>暂无数据</>;}let totalCount = 0;let totalPrice = 0;goods.forEach((good) => {totalCount += good.count;totalPrice += good.price;});return (<>总数量:{totalCount};总价:{totalPrice}</>);
};
如何优化
1. 函数式简洁风格
const GoodList = ({ goods }) => {if (goods.length === 0) {return <>暂无数据</>;}const { totalCount, totalPrice } = goods.reduce((acc, good) => {acc.totalCount += good.count;acc.totalPrice += good.price;return acc;},{ totalCount: 0, totalPrice: 0 })return (<>总数量:{totalCount};总价:{totalPrice}</>);
};
这样做,也可以将变量 totalCount
和 totalPrice
控制在一个函数内,避免中间变量污染上下文。
2. hook 封装(重点)
const useGoodsSummary = (goods: { count: number; price: number }[]) => {return goods.reduce((acc, good) => {acc.totalCount += good.count;acc.totalPrice += good.price;return acc;},{ totalCount: 0, totalPrice: 0 })
};
const GoodList = ({ goods }) => {if (goods.length === 0) {return <>暂无数据</>;}const { totalCount, totalPrice } = useGoodsSummary(goods);return (<>总数量:{totalCount};总价:{totalPrice}</>);
};
3. 性能优化
引入 useMemo
:
function useGoodsSummary(goods: { count: number; price: number }[]) {return useMemo(() => {return goods.reduce((acc, good) => {acc.totalCount += good.count;acc.totalPrice += good.price;return acc;},{ totalCount: 0, totalPrice: 0 });}, [goods]);
}
const GoodList = ({ goods }) => {if (goods.length === 0) {return <>暂无数据</>;}const { totalCount, totalPrice } = useGoodsSummary(goods);return (<>总数量:{totalCount};总价:{totalPrice}</>);
};