Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add component stack info to key validation warnings #6799

Merged
merged 9 commits into from
May 20, 2016
3 changes: 3 additions & 0 deletions src/addons/transitions/ReactTransitionChildMapping.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ var ReactTransitionChildMapping = {
if (!children) {
return children;
}
// TODO: `flattenChildren` now takes an extra `selfDebugID` argument
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@spicyj what's a good way to get and feed debugID to flattenChildren here? The only place that calls ReactTransitionChildMapping.getChildMapping (syntactic sugar for flattenChildren) is here: https://github.com/facebook/react/blob/master/src/addons/transitions/ReactTransitionGroup.js#L41. In other words, how do I/can I get a debugID from a component?

Copy link
Contributor Author

@keyz keyz May 19, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, seems like the only other place we use flattenChildren is in ReactMultiChild and there's already a test for that in ReactMultiChild-test. Interestingly, when ReactChildReconciler finds duplicated keys, the error message talks about "flattenChildren" (which is also test covered in the new ReactChildReconciler-test file).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

var internalInstance = ReactInstanceMap.get(this);
internalInstance._debugID

should work. Maybe someday we'll have a public API to get this that anyone could use but for now I think it's okay for us to get the internal instance for this here.

// for looking up the component stack in dev build.
// Need to figure out a way to get the `_debugID` here.
return flattenChildren(children);
},

Expand Down
5 changes: 3 additions & 2 deletions src/isomorphic/classic/element/ReactElementValidator.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,11 @@ function validateExplicitKey(element, parentType) {
warning(
false,
'Each child in an array or iterator should have a unique "key" prop.' +
'%s%s%s',
'%s%s%s%s',
addenda.parentOrOwner || '',
addenda.childOwner || '',
addenda.url || ''
addenda.url || '',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We shouldn't need these other addenda now since the stack should cover it. Can you remove the code for them? We still will want to dedupe the warnings based on owner though as we're currently doing.

ReactComponentTreeDevtool.getCurrentStackAddendum(element)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ var ReactDOM;
var ReactTestUtils;

describe('ReactElementValidator', function() {
function normalizeCodeLocInfo(str) {
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
}

var ComponentClass;

beforeEach(function() {
Expand Down Expand Up @@ -95,9 +99,10 @@ describe('ReactElementValidator', function() {
ReactTestUtils.renderIntoDocument(<Anonymous>{divs}</Anonymous>);

expect(console.error.argsForCall.length).toBe(1);
expect(console.error.argsForCall[0][0]).toBe(
expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe(
'Warning: Each child in an array or iterator should have a unique ' +
'"key" prop. See https://fb.me/react-warning-keys for more information.'
'"key" prop. See https://fb.me/react-warning-keys for more information.\n' +
' in div (at **)'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice if this had both the parent component (Anonymous, or "Unknown" as we'll know it as in the devtools) and the child (div) here. Is that possible? I guess we would probably have to make getCurrentStackAddendum take both elements as arguments.

);
});

Expand All @@ -111,10 +116,46 @@ describe('ReactElementValidator', function() {
ReactTestUtils.renderIntoDocument(<div>{divs}</div>);

expect(console.error.argsForCall.length).toBe(1);
expect(console.error.argsForCall[0][0]).toBe(
expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe(
'Warning: Each child in an array or iterator should have a unique ' +
'"key" prop. Check the top-level render call using <div>. See ' +
'https://fb.me/react-warning-keys for more information.'
'https://fb.me/react-warning-keys for more information.\n' +
' in div (at **)'
);
});

it('warns for keys with component stack info', function() {
spyOn(console, 'error');

var Component = React.createClass({
render: function() {
return <div>{[<div />, <div />]}</div>;
},
});

var Parent = React.createClass({
render: function() {
return React.cloneElement(this.props.child);
},
});

var GrandParent = React.createClass({
render: function() {
return <Parent child={<Component />} />;
},
});

ReactTestUtils.renderIntoDocument(<GrandParent />);

expect(console.error.argsForCall.length).toBe(1);
expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe(
'Warning: Each child in an array or iterator should have a unique ' +
'"key" prop. Check the render method of `Component`. See ' +
'https://fb.me/react-warning-keys for more information.\n' +
' in div (at **)\n' +
' in Component (at **)\n' +
' in Parent (at **)\n' +
' in GrandParent (at **)'
);
});

Expand Down
52 changes: 29 additions & 23 deletions src/isomorphic/devtools/ReactComponentTreeDevtool.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,28 @@ function purgeDeep(id) {
}
}

function describeComponentFrame(name, source, ownerName) {
return '\n in ' + name + (
source ?
' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' +
source.lineNumber + ')' :
ownerName ?
' (created by ' + ownerName + ')' :
''
);
}

function describeID(id) {
var name = ReactComponentTreeDevtool.getDisplayName(id);
var element = ReactComponentTreeDevtool.getElement(id);
var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeDevtool.getDisplayName(ownerID);
}
return describeComponentFrame(name, element._source, ownerName);
}

var ReactComponentTreeDevtool = {
onSetDisplayName(id, displayName) {
updateTree(id, item => item.displayName = displayName);
Expand Down Expand Up @@ -154,28 +176,6 @@ var ReactComponentTreeDevtool = {
},

getCurrentStackAddendum(topElement) {
function describeComponentFrame(name, source, ownerName) {
return '\n in ' + name + (
source ?
' (at ' + source.fileName.replace(/^.*[\\\/]/, '') + ':' +
source.lineNumber + ')' :
ownerName ?
' (created by ' + ownerName + ')' :
''
);
}

function describeID(id) {
var name = ReactComponentTreeDevtool.getDisplayName(id);
var element = ReactComponentTreeDevtool.getElement(id);
var ownerID = ReactComponentTreeDevtool.getOwnerID(id);
var ownerName;
if (ownerID) {
ownerName = ReactComponentTreeDevtool.getDisplayName(ownerID);
}
return describeComponentFrame(name, element._source, ownerName);
}

var info = '';
if (topElement) {
var type = topElement.type;
Expand All @@ -192,11 +192,17 @@ var ReactComponentTreeDevtool = {

var currentOwner = ReactCurrentOwner.current;
var id = currentOwner && currentOwner._debugID;

info += ReactComponentTreeDevtool.getStackAddendumByID(id);
return info;
},

getStackAddendumByID(id) {
var info = '';
while (id) {
info += describeID(id);
id = ReactComponentTreeDevtool.getParentID(id);
}

return info;
},

Expand Down
31 changes: 26 additions & 5 deletions src/renderers/shared/stack/reconciler/ReactChildReconciler.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,24 @@

var ReactReconciler = require('ReactReconciler');

var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
var instantiateReactComponent = require('instantiateReactComponent');
var KeyEscapeUtils = require('KeyEscapeUtils');
var shouldUpdateReactComponent = require('shouldUpdateReactComponent');
var traverseAllChildren = require('traverseAllChildren');
var warning = require('warning');

function instantiateChild(childInstances, child, name) {
function instantiateChild(childInstances, child, name, selfDebugID) {
// We found a component instance.
var keyUnique = (childInstances[name] === undefined);
if (__DEV__) {
warning(
keyUnique,
'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.',
KeyEscapeUtils.unescape(name)
'the first child will be used.%s',
KeyEscapeUtils.unescape(name),
ReactComponentTreeDevtool.getStackAddendumByID(selfDebugID)
);
}
if (child != null && keyUnique) {
Expand All @@ -50,12 +52,31 @@ var ReactChildReconciler = {
* @return {?object} A set of child instances.
* @internal
*/
instantiateChildren: function(nestedChildNodes, transaction, context) {
instantiateChildren: function(
nestedChildNodes,
transaction,
context,
selfDebugID // __DEV__ only
) {
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);

if (__DEV__) {
traverseAllChildren(
nestedChildNodes,
(childInsts, child, name) => instantiateChild(
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried to put selfDebugID as the first arg of instantiateChild and to use instantiateChild.bind(null, selfDebugID) here, but that means we need to call bind as well in the production build. Do you think the current approach (arrowed currying, if that's a term) is acceptable? @spicyj

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, this seems fine to me. (I think calling it parentDebugID might be a little clearer, but this is also oaky.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, I thought about this; self is more clear to me since we are talking about the current component which happens to be the parent for the children here.

childInsts,
child,
name,
selfDebugID
),
childInstances
);
} else {
traverseAllChildren(nestedChildNodes, instantiateChild, childInstances);
}
return childInstances;
},

Expand Down
4 changes: 2 additions & 2 deletions src/renderers/shared/stack/reconciler/ReactMultiChild.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ var ReactMultiChild = {
try {
ReactCurrentOwner.current = this._currentElement._owner;
return ReactChildReconciler.instantiateChildren(
nestedChildren, transaction, context
nestedChildren, transaction, context, this._debugID
);
} finally {
ReactCurrentOwner.current = null;
Expand All @@ -202,7 +202,7 @@ var ReactMultiChild = {
if (this._currentElement) {
try {
ReactCurrentOwner.current = this._currentElement._owner;
nextChildren = flattenChildren(nextNestedChildrenElements);
nextChildren = flattenChildren(nextNestedChildrenElements, this._debugID);
} finally {
ReactCurrentOwner.current = null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails react-core
*/

// NOTE: We're explicitly not using JSX here. This is intended to test
// the current stack addendum without having source location added by babel.

'use strict';

var React;
var ReactTestUtils;

describe('ReactChildReconciler', function() {
function normalizeCodeLocInfo(str) {
return str.replace(/\(at .+?:\d+\)/g, '(at **)');
}

beforeEach(function() {
jest.resetModuleRegistry();

React = require('React');
ReactTestUtils = require('ReactTestUtils');
});

it('warns for duplicated keys', function() {
spyOn(console, 'error');

var Component = React.createClass({
render() {
return <div>{[<div key="1" />, <div key="1" />]}</div>;
},
});

ReactTestUtils.renderIntoDocument(<Component />);

expect(console.error.argsForCall.length).toBe(1);
expect(console.error.argsForCall[0][0]).toContain(
'Child keys must be unique; when two children share a key, only the first child will be used.'
);
});

it('warns for duplicated keys with component stack info', function() {
spyOn(console, 'error');

var Component = React.createClass({
render: function() {
return <div>{[<div key="1" />, <div key="1" />]}</div>;
},
});

var Parent = React.createClass({
render: function() {
return React.cloneElement(this.props.child);
},
});

var GrandParent = React.createClass({
render: function() {
return <Parent child={<Component />} />;
},
});

ReactTestUtils.renderIntoDocument(<GrandParent />);

expect(console.error.argsForCall.length).toBe(1);
expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe(
'Warning: flattenChildren(...): ' +
'Encountered two children with the same key, `1`. ' +
'Child keys must be unique; when two children share a key, ' +
'only the first child will be used.\n' +
' in div (at **)\n' +
' in Component (at **)\n' +
' in Parent (at **)\n' +
' in GrandParent (at **)'
);
});
});
Loading