我收到了警告 Each child in an array or iterator should have a unique "key" prop. Check the render method of Login
我想要传回一个元素数组,而不使用键.我不得不相信这有一个解决方法,而不添加一个毫无意义的包装器?
请注意
return [<div/>, <div/>];
render () {
return (
<div className='login'>
{this.mobileWeb()}
{this.pcWeb()}
</div>
);
}
mobileWeb () {
if (this.state.isMobileWeb === true) {
return [
<div className='sky-container'></div>,
<div className='sea-container'></div>
];
}
}
pcWeb () {
if (this.state.isMobileWeb !== true) {
return [
<div className='sky-container'></div>,
<div className='sea-container'>
<LoginForm onChange={this.onChange} ref='loginForm' onEmailChange={this.onEmailChange} onPasswordChange={this.onPasswordChange} />
<input type='submit' value='Submit' onClick={this.login} />
</div>
];
}
}
Run Code Online (Sandbox Code Playgroud)
有一个有效的用例不想使用密钥,如果你渲染强烈不同的树(想想博客文章)或者有一个函数返回总是相同的项目数组.
当您不提供显式键时,React将使用索引作为键并发出警告 - 但是您可能希望使警告静音,因为在此处使用索引是完全有效的.
然而,这似乎是不可能的,这会产生令人遗憾的结果,即您必须无条件地使代码更复杂(添加无用的密钥)或忽略警告(这意味着噪声中可能会丢失有效警告) .
截至目前,可能从 16.2.0(2017 年 11 月 28 日)开始,您可以将元素包装在其中<React.Fragment>而不是数组。尽管 s 数组Fragment仍然需要键,但子组件不需要键。
| 归档时间: |
|
| 查看次数: |
2818 次 |
| 最近记录: |