关于React.js循环时出现的警告问题 Warning: Encountered two children with the same key。
Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omi
·
Warning: Encountered two children with the same key
当我们提交一个空数据时,react循环,可能会出现错误警告。
Warning: Encountered two children with the same key, ``. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
in ul (at TodoList.js:33)
in TodoList (at src/index.js:5)
我在这里展示一下,我写的具体代码。
render() {
return (
<Fragment>
<div>
<label htmlFor='inputArea'>请输入内容</label>
<input
id='inputArea'
className='input'
value={this.state.inputValue}
onChange={this.handleInputChange}
/>
<button onClick={this.handleBtnClick}>提交</button>
</div>
<ul>
{this.getTodoItem()}
</ul>
</Fragment>
);
}
getTodoItem() {
return this.state.list.map((item,index) => {
return (
<TodoItem
key={item}//这里我使用的是item作为key值
content={item}
index={index}
deleteItem={this.handleItemDelete}
/>
)
})
}
使用item作为key值,会出现错误,所以,我将key值改成index,测试之后,未发现错误警告,所以,是key值导致这个错误警告
getTodoItem() {
return this.state.list.map((item,index) => {
return (
<TodoItem
key={index}//这里的key值改成index
content={item}
index={index}
deleteItem={this.handleItemDelete}
/>
)
})
}
解决方案: 在当前页面查找key 保证key的唯一性
更多推荐
已为社区贡献1条内容
所有评论(0)