I am using react to create an app. I used create-react-app to setup the project. The following code was used to render the content.
renderVideoShowBlock = () => {
if (this.state.videoRecords) {
return this.state.videoRecords.map((record) => {
console.log("renderVideoShowBlock called", record.id)
return (
<VideoShowBlock
user={this.state.user}
key={record.id}
record={record}
onItemDelete={() => {this.handleVideoItemDelete(record.id)}}
/>
)
})
}
}
the function this.handleVideoItemDelete will make an axios post request to "video/". I find that when this onItemDelete is called in inner modules, the record in closure is always point to the last record in this.state.videoRecords. I use the folowing code to track what happend:
render() {
const videoJsOptions = this.videoJsOptions
const contentBlock = (
<div className='video-box col-lg-6 col-md-8 col-sm-10 col-12
offset-lg-3 offset-md-2 offset-sm-1' >
<VideoPlayer {...videoJsOptions} />
</div>
)
console.log("VideoShowBlock render called")
this.props.onItemDelete()
return (
<ShowBlock user={this.props.user}
author={this.props.record.author}
content={contentBlock}
onItemDelete={this.props.onItemDelete}
/>
)
}
We can see that
console.log("VideoShowBlock render called")
this.props.onItemDelete()
was called sequently. In chrome console, we find:
console.log was called 3 times
but in network tab, we find this.props.onItemDelete was called 6 times, each video record's onItemDelete was called two times.
If I comment this.props.onItemDelete, there will be no request being sent, which means I can not see any request in network tab. It seems like the function was called twice.
Why is that?
As I can see you are calling this.props.onItemDelete()
and you are also passing it in the ShowBlock component what does it do?
return (
<ShowBlock user={this.props.user}
author={this.props.record.author}
content={contentBlock}
onItemDelete={this.props.onItemDelete} // here
/>
)
Maybe you are also calling it in the <ShowBlock/> component that's why the request was sent two times.