path: packages/shared/invariant.js
源码
/**
* 根据条件抛出固定格式的错误,允许使用 %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 的扩展运算符对方法参数做了改造