2014-09-18 39 views

回答

10

ReactJS源使用一个名为__DEV__的变量来跟踪这个变量,但它没有被导出,所以它对你的Mixin不可用。但是,其后果是,例如,当你破坏一个不变量时,开发模式ReactJS会给你一个很好的描述错误的描述。在生产模式下,它会给出一个通用错误,告诉您使用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" 

“渲染”这个词是特定于我们违反的不变量,所以它只在dev版本的异常中出现。

相关问题