鉴于此代码,React会发出警告,指出在包装div
上没有指定唯一键,尽管不需要它,因为所有子组件都指定了键。
class exampleComponent extends React.Component {
render() {
return (
<div>
{this.state.data.map(({uniqueId, xData}) => {
const bar = xData.map(({id}) => (
<X key={id}/>
));
const foo = <foo key={uniqueId}/>;
return (
<div> { /* No key in here, as it's not needed. Throws a warning */}
{foo}
{bar}
</div>
);
});
}
</div>
);
}
}
答案 0 :(得分:1)
您应该设置为父key
,而不是为<foo />
组件设置<div>
道具。
工作示例:
class exampleComponent extends React.Component {
render() {
return (
<div>
{this.state.data.map(({uniqueId, xData}) => {
const bar = xData.map(({id}) => (
<X key={id}/>
));
return (
<div key={uniqueId}>
<foo />
{bar}
</div>
);
});
}
</div>
);
}
}