我经常遇到基本助手函数的代码重复问题,如下所示:
function percentageWithCommas(x?) { try { return (x * 100).toLocaleString("en-UK", { maximumFractionDigits: 1 }) + '%'; } catch (e) { return (x * 100).toFixed(2) + '%'; } }
我在不同文件夹中的许多TSX文件中发现了这个特定的功能,例如 myView1/components/fileA.tsx , myView2/components/fileB.tsx , myView2/components/fileC.tsx .
myView1/components/fileA.tsx
myView2/components/fileB.tsx
myView2/components/fileC.tsx
我怎样才能快速重构它,这样我只需要在 一 地点?我觉得有一个原因,我的前任没有写一个组成部分。
创建一个utils模块,添加一个文件并把这些东西粘在里面。然后在需要的地方从中导入模块或所需的函数。
src/utils/index.js
export function percentageWithCommas(x?) { try { return (x * 100).toLocaleString("en-UK", { maximumFractionDigits: 1 }) + '%'; } catch (e) { return (x * 100).toFixed(2) + '%'; } }
src/组件/组件a.js
import { percentageWithCommas } from '../utils'; export default ComponentA = props => { const formattedPercent = percentageWithCommas(0.05); // '5%' ... }