在使用 reportWebVitals 函数报告网站关键性能指标时,需要显式地返回一个值。如果没有返回值,会导致类型错误。以下是示例代码,演示如何添加返回类型:
import reportWebVitals from './reportWebVitals';
function sendToAnalytics(metric) {
const report = { ...metric, startTime: undefined, value: metric.value.toFixed(2) };
navigator.sendBeacon('/analytics', JSON.stringify(report));
}
reportWebVitals((metric) => {
switch (metric.name) {
case 'first-contentful-paint':
// Without return type
sendToAnalytics(metric);
break;
case 'largest-contentful-paint':
// With return type
return sendToAnalytics(metric);
case 'cumulative-layout-shift':
// With return type
return sendToAnalytics(metric);
default:
break;
}
});
在此示例中,我们添加了 return
来显式地返回 sendToAnalytics
函数的返回值。这样就可以避免类型错误,并确保适当地报告网站的关键性能指标。
上一篇:报告“按类型查询”的分析