简体   繁体   English

如何从生产构建中排除钩子

[英]How do I exclude a hook from a production build

I have created a hook that prints some debug information, which in turn calls some of Reacts hooks.我创建了一个打印一些调试信息的钩子,它又调用了一些 Reacts 钩子。 I would like to automatically exclude it from the production build.我想自动将其从生产版本中排除。 If I try to do it with an if statement like this:如果我尝试使用这样的 if 语句来做到这一点:

if (process.env.NODE_ENV === 'development') {
        useMyHook(...)
}

I get the error React Hook "useMyHook" is called conditionally. React Hooks must be called in the exact same order in every component render我收到错误React Hook "useMyHook" is called conditionally. React Hooks must be called in the exact same order in every component render React Hook "useMyHook" is called conditionally. React Hooks must be called in the exact same order in every component render . React Hook "useMyHook" is called conditionally. React Hooks must be called in the exact same order in every component render In this case the hooks would still be called in order though.在这种情况下,仍然会按顺序调用挂钩。

How can I exclude a hook in a production build?如何在生产构建中排除钩子?

You can wrap the logic inside useMyHook with if (process.env.NODE_ENV === 'development') condition.您可以使用if (process.env.NODE_ENV === 'development')条件将逻辑包装在useMyHook中。

You can check out Rules of Hooks from React documentation for a neat explanation.您可以查看 React 文档中的“挂钩规则”以获得简洁的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM