条件判断
传入index,
if(this.state.isshow){
person=(
<div>
{
this.state.persons.map((person,index)=>{
return <Person
name={person.name}
age={person.age}
click={this.deletePersonHandler.bind(this,index)}
/>
})
}
</div>
);
}else{
person=null;
}
对array进行splice操作
注意const persons为指向array的指针,该array可以被改变,而persons并未被改变;
deletePersonHandler=(personIndex)=>{
const persons = this.state.persons;
persons.splice(personIndex,1);
this.setState({persons:persons});
}
缺点
上述代码的person为state.persons的地址,splice改地址的array会造成不稳定因素;
优化
改变改array的copy,再传回;
方法1:slice
deletePersonHandler=(personIndex)=>{
const persons = this.state.persons.slice(); //返回一个copy
persons.splice(personIndex,1);
this.setState({persons:persons});
}
方法2:…
deletePersonHandler=(personIndex)=>{
const persons = [...this.state.persons]; //内容复制
persons.splice(personIndex,1);
this.setState({persons:persons});
}
这篇博客探讨了在React中如何实现点击删除功能。首先介绍了通过条件判断和使用`splice`方法来操作数组,然后指出直接修改state中引用类型的危险性,可能导致组件状态不稳。接着,提出了两种优化方案:一是利用`slice`创建数组副本进行修改,二是使用扩展运算符(...)来复制并更新数组。
4017

被折叠的 条评论
为什么被折叠?



