ReactJS源代码使用一个名为 __DEV__
的变量来跟踪此问题,但它未被导出,因此在您的Mixin中无法使用。
然而其后果是明显的。例如,当您违反不变性条件时,dev模式的ReactJS将会给出详细的错误描述;在生产模式下,它将提供一个通用错误,告诉你使用dev版本。
我们可以利用这个特性来构建一个函数来判断React是否处于dev模式:
function isDevReact() {
try {
React.createClass({});
} catch(e) {
if (e.message.indexOf('render') >= 0) {
return true; // A nice, specific error message
} else {
return false; // A generic error message
}
}
return false; // should never happen, but play it safe.
};
之所以有效,是因为在这两种模式下,未实现render
方法的异常情况不同:
Development: "Invariant Violation: createClass(...): Class specification must implement a `render` method. Inline JSX script:16"
Production: "Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings. Inline JSX script:16"
“Render”这个词是特定于我们违反的不变量的,因此它只会在开发版本的异常中出现。
__DEV__
变量。 - Konstantin Tarkus