有没有办法检查React' s“ strictmode”是否已打开?
在代码中或通过React DevTools中有一种方法,以查看
需要明确的是,这个问题是:
- 不是关于如何启用严格模式的。 (答案是
< react.strictmode>
,尽管也可以通过某些框架中的配置设置它,例如,next.js
) - 专门讨论了React
stricts strictmode在/a>(
'使用strart';
)或 typescript> typescript的严格模式。这是一个超载的短语,但是Watcha会这样做吗? - 由于与React的Strictmode意外渲染的意外渲染,您的混乱动机。请参阅 this github问题或此stackoverflow post 为了使其造成挫败感。即使您无法启用了“ strictmode”中的何处,也可以使用一种简单的方法来验证组件正在严格模式中运行。
Is there a way in React -- either in code or via the React devtools -- to see if a component is being rendered in React's StrictMode
? In my dream world, there would be some kind of constant I could console.log
, say a bool of React.isStrictModeOnForThisComponentRendering
; or maybe when you inspect a component in the React devtools, it would say somewhere in the side panel if it's rendering in StrictMode or not.
To be clear, this question is:
- Not about how do you enable StrictMode. (The answer is
<React.StrictMode>
, although it can also be set via configs in some frameworks, e.g.,Next.js
) - Specifically discussing React's
StrictMode
, not JavaScript's ('use strict';
) or TypeScript's strict mode. It's an overloaded phrase, but watcha gonna do? - Motivated by the confusion you get due to unexpected double rendering with React's StrictMode. See this GitHub issue or this StackOverflow post for a sense of the frustration it can cause. It would be nice to have an easy way to verify a component is running in StrictMode even if you can't tell where in the component tree StrictMode has been enabled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是一种清晰或确定的方式,但是您可以有目的地触发仅在React的Strictmode中发生的警告。例如:
无论如何,此警告将包含一些类似的文本,
这些文本似乎是相当不错的证明,证明该组件正在strictmode中呈现。拥有更直接的辅助功能会很好,但是它可以捏合。
It's not a clear or definitive way, but you can purposefully trigger a warning that is supposed to only occur in React's StrictMode. For example:
In any case, this warning will contain some text like this
which seems like reasonably good proof that the component is rendering in StrictMode. Would be nice to have a more direct helper function, but it works in a pinch.