Pergunta

Since the latest version of ReactJS we have a warning that asks to add keys for dynamic children. I had some troubles to found which component was generating this warning... I first assumed that only the child that were generated dynamically in a "for loop" would throw this warning (since it's "generated dynamically"). Finally, I found that every components of our application throw this error because we have children everywhere (even if we don't have a "for loop") :(

We are using CoffeeScript and I'm asking myself if we are using ReactJS in the correct way:

DOM = React.DOM
myComponent = React.createClass
  render: ->
    DOM.div {className: "app", ref: "app"},
      DOM.div {className: "child1"}, "This is a test" # throw warning
      DOM.div {className: "child2", key: "child2"}, "Hello" # don't throw warning

Here child1 is throwing a warning unless we add a key attribute. Is this behavior normal ? Are we doing something wrong ? What I mean is that we need to add keys to more than 500 components/children which is a hard and boring work...

Also, the warning says that the function "undefined" is throwing it. So I need to dig around 10min to 1h everytime to check where to correct things... :(

Best regards, Kursion

Foi útil?

Solução

There are 2 things going on here, so let's separate them…

Here child1 is throwing a warning unless we add a key attribute. Is this behavior normal ? Are we doing something wrong ? What I mean is that we need to add keys to more than 500 components/children which is a hard and boring work...

  1. As @FakeRainBrigand mentioned, this sample code shouldn't be warning about keys. and in fact it doesn't - http://jsfiddle.net/zpao/5KSah/. The way we made this warning work is by detecting if an array was passed as an argument.
  2. If you have 500 children, then I have a lot of trouble believing you don't have an array in there.

Also, the warning says that the function "undefined" is throwing it

This is because React uses a property called displayName (specified on the object passed to createClass) to build that warning. When using JSX, we can autogenerate that property for you based on assignment. It's not always perfect but it usually works well enough. When using CoffeeScript, you may want to specify this property yourself.

/** @jsx React.DOM */
var MyComponent = React.createClass({ ... });
// becomes
var MyComponent = React.createClass({displayName: 'MyComponent', ... });
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top