javascript 当 propTypes 验证失败时,强制 ReactJS 抛出真正的错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27006782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force ReactJS to throw real errors when propTypes validation fails?
提问by nrabinowitz
At present, if propType
validation fails, ReactJS uses console.warn
to emit a warning. I really, really want a real error in dev mode, so it can fail our continuous integration build, instead of just printing a message that might be lost in the shuffle.
目前,如果propType
验证失败,ReactJSconsole.warn
会发出警告。我真的,真的很想在开发模式下出现一个真正的错误,所以它可能会使我们的持续集成构建失败,而不仅仅是打印一条可能在 shuffle 中丢失的消息。
There's already been discussion of this, e.g. in this feature request, and this related questiondescribes the current behavior as expected. That's fine, but I personally want it to throw an error.
已经对此进行了讨论,例如在此功能请求中,并且此相关问题按预期描述了当前行为。这很好,但我个人希望它抛出一个错误。
Assuming that ReactJS doesn't provide better support for this any time soon, what's the best workaround?So far, the best I've come up with is to override console.warn
for tests, e.g.
假设 ReactJS 不会很快为此提供更好的支持,那么最好的解决方法是什么?到目前为止,我想出的最好的方法是覆盖console.warn
测试,例如
console.warn = function(msg) {
throw new Error(msg);
};
The downside of this is, it can be tricky to implement in tests, and it's not React-specific, so other console.warn
calls also need to be handled.
这样做的缺点是,在测试中实现可能很棘手,而且它不是特定于 React 的,因此console.warn
还需要处理其他调用。
采纳答案by lobati
From this answer, you can check the error message against typical react messages and only throw for those. Not perfect, but maybe a step closer to what you're looking for:
从这个答案中,您可以根据典型的反应消息检查错误消息,并且只针对这些消息抛出。不完美,但可能更接近您要查找的内容:
let warn = console.warn;
console.warn = function(warning) {
if (/(Invalid prop|Failed propType)/.test(warning)) {
throw new Error(warning);
}
warn.apply(console, arguments);
};
回答by Michael Martin
FlowType, introduced by Facebook yesterday sounds like exactly what you're after. It can analyse your code, infer types, and throw errors at compile time.
昨天 Facebook 推出的 FlowType 听起来正是您所追求的。它可以分析您的代码、推断类型并在编译时抛出错误。
It specifically includes support for React and the propTypes argument: http://flowtype.org/docs/react-example.html#property-use
它特别包括对 React 和 propTypes 参数的支持:http://flowtype.org/docs/react-example.html#property-use