[英]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.