I'm using react to write a page to show pictures in browser. I'm using the following code to render a picture-show-block
renderPicShowBlock= () => {
if (this.state.records)
{
let picBlocks = []
for (const record of this.state.records) {
picBlocks.push(
<PicShowBlock user={this.state.user}
key={record.id}
record={record}
onItemDelete={()=>this.handleItemDelete(record.id)}
/>
)
}
return picBlocks
} else {
return null
}
}
handleItemDelete is defined as an arrow function:
handleItemDelete= (id) => {
axios.post("/core/data/record/",
{"action": "delete", "item_id": id}).then((response)=>{
console.log(response.data)
this.init_record()
})
}
The problem is when I call onItemDelete in this component, the record in this closure get stuck pointing to the last record in this.state.records. I was thinking that it might be that "JS closure trap" caused by JS glocal scpoe, but it seems not. What does this problem come from? Is that caused by closure or some code logic bugs?
I used create-react-app to setup this project.
You can turn it around:
<PicShowBlock user={this.state.user}
key={record.id}
record={record}
onItemDelete={this.handleItemDelete(record.id)}
/>
and
handleItemDelete= (id) => () => {
axios.post("/core/data/record/",
{"action": "delete", "item_id": id}).then((response)=>{
console.log(response.data)
this.init_record()
})
}
This way, this.handleItemDelete(record.id) will be executed immediately with the right record and the function just returns the callback you want on your component.
Oh, I found that it was caused by another issue. It is because that the logic to process deletebutton's id is wrong, The Bootstrap's javascript pick another delete button from anothor ShowBlock