关于React.js循环时出现的警告问题 Warning: Encountered two children with the same key。

2 篇文章 0 订阅
1 篇文章 0 订阅

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的唯一性
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值