React 深度学习:invariant

path: packages/shared/invariant.jses6

源码

/** * 根据条件抛出固定格式的错误,容许使用 %s 做为变量的占位符 * * @param condition * @param format * @param a * @param b * @param c * @param d * @param e * @param f */
export default function invariant(condition, format, a, b, c, d, e, f) {
  validateFormat(format);

  if (!condition) {
    let error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.',
      );
    } else {
      const args = [a, b, c, d, e, f];
      let argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        }),
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}
复制代码

从上面的代码,从中能够看到:函数

  • 使用 %s 做为占位符的字符串替换手段,这在 Java 语言的工具中常会见到。
  • .replace 方法 能够接受一个函数做为第二个参数,这个函数用来建立新子字符串。当他跟正则的 g 标志配置使用的时候,该函数会在每一个匹配到的字符串时被调用。

但这个函数有一个缺陷,就是只能支持最多 6 个占位符。工具

扩展

export default function invariant(condition, format, ...args) {
  validateFormat(format);

  if (!condition) {
    let error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.',
      );
    } else {
      let argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        }),
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}
复制代码

只是简单作了很小的修改,使用 es6 的扩展运算符对方法参数作了改造ui

相关文章
相关标签/搜索