欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > WHAT - React 使用 Hook 分离计算逻辑与渲染逻辑

WHAT - React 使用 Hook 分离计算逻辑与渲染逻辑

2025/4/18 22:24:03 来源:https://blog.csdn.net/weixin_58540586/article/details/147065558  浏览:    关键词:WHAT - React 使用 Hook 分离计算逻辑与渲染逻辑

目录

  • 原始代码
  • 如何优化
    • 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}</>);
};

这样做,也可以将变量 totalCounttotalPrice 控制在一个函数内,避免中间变量污染上下文。

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}</>);
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词