[英]Component List don't update state after deleting one item
我在尝试更新通过映射字符串列表创建的有状态组件列表时遇到问题。 当我通过切片数组以通过其索引删除元素来删除此组件之一时,问题就显示出来了。
每个组件都有自己的状态,即从API获取。 问题是,当我删除数组的元素时,下一个组件的状态与我删除了Component的状态重叠。
我的代码类似于以下内容:
class MyDashboard extends React.Component {
constructor(props){
super(props);
this.state = {
activeItems: [0,1,2,3],
}
this.removeItem = this.removeItem.bind(this);
}
removeItem(indx){
let tempItems= this.state.activeItems;
tempItems.splice(indx,1);
this.setState({activeItems:tempItems});
}
render(){
let conditionalDash;
let conditionalComponent;
let temporalArray = this.state.activeEntries.map((entry , i) => {
return (<MyDash key={i} index {i}/> removeItem={this.removeItem});
});
render(){
return (
<div id='dashContainer'>
{temporalArray}
</div>
)
}
}
在我的MyDashComponent中,我有一个类似的东西:
class MyDash extends React.Component{
constructor(props){
super(props);
this.state={
fetchedData:null,
}
}
componentDidMount(){
API.fetchData(this.props.index).then(response => {
this.setState({fetchData:response.data})
)
}
render(){
return(
<div> {this.props.index} {this.state.fetchedData}</div>
)
}
}
有什么我想念的吗?
我得到的行为是,当我删除this.state.activeItems [2]时,此元素的状态与先前的组件相同。 我期望element [2]的状态与具有element [3]的状态相同。
编辑:我忘了告诉我的是,MyDash组件的属性正确,只是状态不属于该组件,而是来自已删除的组件。
感谢您的阅读,我希望有人可以帮助我。
谁混合了行为或slice
和splice
slice
返回一个新数组,而splice
修改现有数组
根据MDN文档:
splice:
splice()
方法通过删除现有元素和/或添加新元素来更改数组的内容。语法:array.splice(开始,删除计数)
slice:
slice()
方法将数组一部分的浅表副本返回到从头到尾选择的新数组对象中(不包括end)。 原始数组将不会被修改。句法:
arr.slice() arr.slice(begin) arr.slice(begin, end)
您可以将代码更改为
removeItem(indx){
let tempItems= this.state.activeItems;
tempItems.splice(indx,1);
this.setState({ activeItems:tempItems });
}
同样,您不应该直接改变状态,您应该创建状态数组的副本,然后对其进行更新。
removeItem(indx){
let tempItems= [...this.state.activeItems]; // this is do a shallow copy, you could use something else depending on your usecase
tempItems.splice(indx,1);
this.setState({ activeItems:tempItems });
}
您还可以使用Array.prototype.filter删除该项目:
removeItem(indx) {
this.setState({
activeItems: this.state.activeItems.filter((_, index) => index !== idx),
})
}
要么
removeItem(indx) {
this.setState(prevState => ({
activeItems: prevState.activeItems.filter((_, index) => index !== idx),
}))
}
我发现错误是我正在使用的列表的键,它是map方法的索引,我读到它必须是唯一键。 幸运的是,此操作修复了渲染操作,状态不再重叠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.