React中为什么要使用key
2019-03-28 12:58
351 查看
开发中我们经常会遇到循环渲染某个组件的情况,以React为例,父组件Father中渲染Son组件:
import React from 'react'; import ReactDOM from 'react-dom'; // 组件 class Test extends React.Component{ constructor(){ super(); this.state = { students: [ { name: 'tom', id: '001' }, { name: 'jack', id: '002'}, { name: 'lucy', id: '003'}, { name: 'alice', id: '004'} ] } } handClick(){ this.state.students.shift(); this.setState({ students: this.state.students }) } render(){ // console.log(this.state.arr); return <div> { this.state.students.map((item, index)=>{ return <div> <input type="radio"/> 姓名:{item.name} id: {item.id} </div>; }) } <button onClick={()=>this.handClick()}>删除第一项</button> </div> } } // 组件渲染 ReactDOM.render(<div><Father></Father></div>, document.getElementById('app'));
运行后结果如图
那么这时,问题来了,当我们点击第三个学生lucy后,点击删除按钮会发生什么情况呢?
lucy的选中状态被添加到了alice上,上一个的选中状态没有跟随组件的变化而变化
那么在我们为组件添加key绑定 key={XXX}
// 添加了 key={item.id} // 注意,千万不要为了方便把key的值设为map函数中的index,因为这样不能区分唯一确定每一项的不同,虽然这样过后浏览器不会再出现warning,但是渲染时还是会出现上述选中状态不跟随的情况 render(){ return <div> 3ff7 { this.state.students.map((item, index)=>{ return <div key={item.id}> <input type="radio"/> 姓名:{item.name} id: {item.id} </div>; }) } <button onClick={()=>this.handClick()}>删除第一项</button> </div> }
现在选中状态会跟随选中内容了!
相关文章推荐
- 为什么使用React
- 详解React之key的使用和实践
- React-为什么要使用虚拟DOM
- [置顶] React中一个没人能解释清楚的问题——为什么要使用Virtual DOM
- 为什么使用 React? Edit on GitHub
- 为什么要使用 Vue.set(object, key, value)
- 为什么使用 React? Edit on GitHub
- APP为什么签名,使用keytool jarsigner进行签名
- React 等框架使用 index 做 key 的问题
- React中使用collections时key的重要性详解
- 为什么使用ReactNative?
- 为什么在 React 的 Render 中使用箭头函数和 bind 会造成问题
- APP为什么签名,使用keytool jarsigner进行签名
- react 中为什么在数组遍历时要给一个key值
- react native key,ref,bind的作用和使用
- 我为什么放弃 React 而使用 Vue?
- react中key的使用
- 为什么 react 中要使用 redux
- react中为什么要使用immutable
- 详解React之key的使用和实践