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