删除项目后反应列表呈现错误数据 [英] React list rendering wrong data after deleting item
问题描述
我有一个简单的学生对象列表,其中包含名称和状态分数.
他们的名字绑定到{student.name}
,他们的分数绑定到
每当我想从这个列表中删除第一个学生时通过调用 set state 重新渲染组件.
第二个学生的输入标签显示第一个学生的分数而不是自己的.为什么会在我做错的地方发生这种情况??
class App 扩展 React.Component{构造函数(){极好的();this.state ={学生:[{name:A",score:10},{name:B",score:20},{name:C",score:30}]}}onDelete(索引){this.state.students.splice(index,1);this.setState(this.state);}使成为(){返回(<div>{this.state.students.map((student,index)=>{返回(<div key={index}><b>{student.name}</b>- <输入类型=文本"defaultValue={student.score}/><button onClick={this.onDelete.bind(this,index)}>delete</button>
)})}
)}}ReactDOM.render(
这是因为您使用的是 key={index}
而不是学生独有的值.
当数组被修改时,删除索引后的学生将拥有错误的键,并且 React 不会注册键更改以使用更新后的数据重新呈现.
你应该使用这样的东西......
假设 student.name
是唯一的.
I have a simple list of student objects with name and their scores in state.
Their name is bound to <b>{student.name}</b>
and their score is bound to
<input type="text" defaultValue={student.score}/>
Whenever I want to delete the first student from this list and
re-rendering the component by calling set state.
The input tag of the second student showing the score of the first student instead of having its own. Why this happening where I am doing it wrong ??
class App extends React.Component{
constructor(){
super();
this.state ={
students:[{name:"A",score:10},{name:"B",score:20},{name:"C",score:30}]
}
}
onDelete(index){
this.state.students.splice(index,1);
this.setState(this.state);
}
render(){
return(
<div>
{this.state.students.map((student,index)=>{
return(
<div key={index}>
<b>{student.name}</b> - <input type="text" defaultValue={student.score}/>
<button onClick={this.onDelete.bind(this,index)}>delete</button>
</div>
)
})}
</div>
)
}
}
ReactDOM.render(<App/>,document.getElementById("main"));
解决方案 It's because you're using key={index}
instead of a value unique to the student.
When the array is modified the students after the index removed will have the wrong key and React will not register a key change to rerender with the updated data.
You should instead use something like this...
<div key={student.name}>
assuming that student.name
is unique.
这篇关于删除项目后反应列表呈现错误数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文