我在尝试更新通过映射字符串列表创建的有状态组件列表时遇到问题。当我通过切片数组以按索引删除元素来删除其中一个组件时,问题就出现了。
每个组件都有自己的状态,我从 API 获取该状态。问题是,当我删除数组的一个元素时,下一个组件的状态与我删除的组件的状态重叠。
我的代码看起来与此类似:
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] 时,该元素的状态与前一个组件相同。我期望元素 [2] 的状态与元素 [3] 的状态相同。
编辑: 我忘记告诉大家的是,MyDash 组件的 props 是正确的,只是不属于该组件的状态,它来自已删除的组件。
感谢您的阅读,我希望有人可以帮助我。
最佳答案
我发现错误是我正在使用的列表的键,它是映射方法的索引,我读到它必须是唯一的键。幸运的是,这修复了渲染操作并且状态不再重叠。
关于javascript - 删除一项后组件列表不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47766327/