如何判断反应功能组件是否已在代码中呈现?
我正在尝试添加一些日志记录,以查看在React中渲染功能组件所需的时间。对我来说,棘手的部分是如何实际分辨何时渲染组件。通过“渲染”,这意味着用户可以在前端看到它(该组件中的所有部分都应显示)。我正在尝试使用使用来实现这一目标,因为它可以确定何时安装组件。
代码类似于下面:
function showComponent() {
console.log('start rendering....start timer');
console.log(new Date().getTime());
setStoreViewState('foobar');
}
observer(function Component() {
React.useEffect(() => {
console.log('rendering complete....stop timer');
console.log(new Date().getTime());
}, []);
......
const thingsToShow = getStoreViewState();
return (<div>{thingsToShow}</div>)
}
我想知道这是否是实现此目标的准确方法。谢谢!
I am trying to add some logging to see how much time it takes to render a functional component in React. The tricky part to me is how to actually tell when the component has been rendered. By "rendered", it means the user can see it in the front end (all parts in that component should be displayed). I am trying to use useEffect to achieve this, as it can tell when the component is mounted.
The code is something like below:
function showComponent() {
console.log('start rendering....start timer');
console.log(new Date().getTime());
setStoreViewState('foobar');
}
observer(function Component() {
React.useEffect(() => {
console.log('rendering complete....stop timer');
console.log(new Date().getTime());
}, []);
......
const thingsToShow = getStoreViewState();
return (<div>{thingsToShow}</div>)
}
I am wondering if this is an accurate way to achieve this. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据文档,没有依赖性的使用效率意味着它已经完成渲染。
https://reactjs.org/docs/hooks/hooks/hooks-effect..html另外,不要忘记,直到浏览器绘制后,React Defer运行使用效果,因此额外的工作少即问题。
上面的引用来自文档。
According to the docs, the useEffect with no dependency means that it has finished rendering.
https://reactjs.org/docs/hooks-effect.html
Also, don’t forget that React defers running useEffect until after the browser has painted, so doing extra work is less of a problem.
The quote above is from the docs.