我搜索了unescape
翻遍了React(15.4版本)的源码,只发现一处使用了它。该文件是react/lib/flattenChildren.js
:
function flattenSingleChildIntoContext(traverseContext, child, name, selfDebugID) {
// We found a component instance.
if (traverseContext && typeof traverseContext === 'object') {
var result = traverseContext;
var keyUnique = result[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('./ReactComponentTreeHook');
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (keyUnique && child != null) {
result[name] = child;
}
}
}
它是在flattenSingleChildIntoContext
- 它在堆栈跟踪中的显示方式。有问题的行尝试显示警告:
process.env.NODE_ENV !== 'production' ? warning(false, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
这意味着最大调用堆栈错误仅发生在开发模式下。问题是你正在某个地方渲染两个或多个具有相同键的元素。要知道关键是什么,您可以在 Chrome 开发工具中的这一行中使用断点。或者您可以添加console.log
在那里并抛出异常,以便它立即停止执行:
if (!keyUnique) {
console.log('key is not unique', name);
throw new Error('Key is not unique');
}
如果您以这种方式获得密钥,您将能够找到具有重复密钥的元素的位置。