[英]removing object in an array based on one of it's properties
我試圖操縱狀態內部的一組組件,並且我希望能夠根據其id
屬性刪除每個組件。 每次創建組件時動態傳遞id
時,我無法弄清楚如何定位該組件。
constructor(props) {
super(props);
this.state = {
counters: 0, // counters count
countersArr: []
}}
render() {
let countersArrCop = this.state.countersArr;
let counterIndex;
onAddCounterHandler = () => {
const id = new Date().getTime()
console.log(this.state.countersArr.length)
console.log(counterIndex)
countersArrCop.push( // push new counter to the counters holder
<Counter
style={styles.countersContainer}
key={id}
id={id}
remove={() => removeCounterHandler(id)}
/>
)
this.setState({
countersArr: countersArrCop,
})
console.log(id)
}
// remove counter
removeCounterHandler = (id) => {
console.log(id)
const countersArr = this.state.countersArr.slice(); // Local copy to manipulate
this.setState({ countersArr: countersArr.filter(counter => counter.id !== id) });
}
return (
<View style={styles.container}>
<View style={styles.addBtnContainer}>
<Button
onPress={onAddCounterHandler}
title={'add Counter'}
/>
</View>
{
/* return each individual counter from the array by using 'map' */
}
<View style={styles.container}> {
this.state.countersArr.map((counter) => {
return counter;
})
}
</View>
</View>
);
更新了代碼*** id
=== undefined
..為什么?
首先不建議將邏輯代碼放入render()
中。 render應該只進行渲染,其他任何任務都應該放在應有的位置。 請注意, 每次重新渲染組件時,渲染塊中的所有代碼都會被調用。 因此,這些處理應被聲明為從適當的鈎組件類中的方法渲染如可能onClick()
不要忘記你的綁定this
背景下這樣您保留this
參考你的方法內部組件類:
<Button onClick={this.onAddCounterHandler.bind(this)} />
第二,當您僅將ID存儲在數組中時,就會用一組組件膨脹狀態:
onAddCounterHandler() {
const { countersArr } = this.state
const id = new Date().getTime()
this.setState({
countersArr: [...countersArr, id],
})
}
然后只需映射該數組並返回如下組件:
{ this.state.countersArr.map(id=>
<Counter
style={styles.countersContainer}
key={id}
id={id}
remove={this.removeCounterHandler.bind(this, id)}
/>
) }
請注意,在jsx中,此語句應放在大括號{}中
然后在您的過濾功能上:
removeCounterHandler(filteredID) {
const { countersArr } = this.state
const filtered = countersArr.filter(id=>id!==filteredID)
this.setState({ countersArr: filtered});
}
最后,永遠不要將setState放入渲染器中
試試看,讓我知道它如何進行:)
您可以執行以下功能:
removeCounterHandler (id) {
const countersArr = this.state.countersArr.slice(); // Local copy to manipulate
this.setState({ countersArr: countersArr.filter(counter => counter.id !== id) });
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.