自最新版本的 ReactJS 以来,我们有一个警告,要求为动态子项添加键。 我很难找到哪个组件生成此警告...我首先假设只有在“for 循环”中动态生成的子项才会抛出此警告(因为它是“动态生成的”)。最后,我发现我们应用程序的每个组件都会抛出这个错误,因为我们到处都有 child (即使我们没有“for 循环”):(
我们正在使用 CoffeeScript,我问自己我们是否以正确的方式使用 ReactJS:
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
除非我们添加 key 属性,否则 child1 会发出警告。这种行为正常吗?我们做错了什么吗?我的意思是,我们需要为超过 500 个组件/子组件添加键,这是一项艰巨而枯燥的工作......
另外,警告说函数“undefined”正在抛出它。所以我每次都需要挖掘大约 10 分钟到 1 小时,以检查哪里可以纠正错误...:(
最好的问候, 库尔申
最佳答案
这里有两件事,所以让我们把它们分开......
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...
- 正如@FakeRainBrigand 所提到的,此示例代码不应针对键发出警告。事实上它没有 - http://jsfiddle.net/zpao/5KSah/ .我们使此警告起作用的方法是检测是否将数组作为参数传递。
- 如果您有 500 个 child ,那么我很难相信您那里没有数组。
Also, the warning says that the function "undefined" is throwing it
这是因为 React 使用名为 displayName
的属性(在传递给 createClass
的对象上指定)来构建该警告。使用 JSX 时,我们可以根据分配自动为您生成该属性。它并不总是完美的,但通常效果很好。使用 CoffeeScript 时,您可能希望自己指定此属性。
/** @jsx React.DOM */
var MyComponent = React.createClass({ ... });
// becomes
var MyComponent = React.createClass({displayName: 'MyComponent', ... });
关于javascript - 带键的 ReactJS 动态子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22422584/