嗨,我只是next.js的新手,然后做出反应。我只是发现next.js具有内置功能,可以将性能指标(例如,fcp)记录到控制台中,我希望将其显示在我的 Metric 组件中 https://nextjs.org/docs/advanced-features/measuring-performance
这是我的 Metric 组件:
export let fcpTime = 0;
const Metric = () => {
// display metrics
useEffect(() => {
console.log("fcpTime: ", fcpTime); // fcpTime still = 0
}, []);
}
export default Metric;
我试图在fcpTime
内设置case 'FCP':
// pages/_app.js
export function reportWebVitals(metric) {
switch (metric.name) {
case 'FCP':
// handle FCP results
fcpTime = metric.value;
break
case 'LCP':
// handle LCP results
break
case 'CLS':
// handle CLS results
break
case 'FID':
// handle FID results
break
case 'TTFB':
// handle TTFB results
break
default:
break
}
}
但是,如何记录FCP结果时如何将FCP结果传递到我的组件并使其重新呈现?谢谢。
答案 0 :(得分:1)
最后,我调度了new CustomEvent
并使用Effect将EventListener添加到此自定义事件中。这是代码:
_app.js
export function reportWebVitals(result) {
if (result.name === "FCP") {
dispatchFcpEvent(result);
}
};
Metric.js
let fcpEvent = null;
export const dispatchFcpEvent = (fcp) => {
fcpEvent = new CustomEvent('fcpTime', { detail: fcp.value });
window.dispatchEvent(fcpEvent);
}
const Copyright = () => {
const [fcpTime, setFcpTime] = useState();
if (typeof window !== "undefined") {
const onFcpTimeUpdate = (e) => {
setFcpTime(e.detail);
window.removeEventListener('fcpTime', onFcpTimeUpdate, false);
};
useEffect(() => {
window.addEventListener('fcpTime', onFcpTimeUpdate);
}, []);
}
// return below
...
}