我在componentDidMount中有 React Component从服务器获取数据。问题是componentDidMount被调用了两次,API 也被调用了两次。由于两次 API 调用,我有一个视图增量 API,例如 youtube 视频视图在数据库中增加了两次。class SingleVideoPlay extends React.Component { constructor(props) { super(props); this.player = React.createRef(); } state = { autoPlay: true, relatedVideos: [], video: null, user: null, comments: [], commentInput: { value: '', touch: false, error: false }, following: false, tab: 'comments' }; _Mounted = false; componentDidMount() { this._Mounted = true; if (this._Mounted) { const videoId = this.props.match.params.id; this.getVideoDetails(videoId); } } componentWillUnmount() { this._Mounted = false; try { clearInterval(this.state.videoInterval); this.props.videoEditUrl(''); } catch (error) {} } captureVideoTime = async () => { const { video } = this.state; const result = await updateWatchTime({ id: video._id, time: 1 }); if (result.status === 200) { const updateVideo = { ...video, secondsWatched: video.secondsWatched + 1 }; this.setState({ video: updateVideo }); } }; videoEnded = () => { clearInterval(this.state.videoInterval); }; videoPause = () => { clearInterval(this.state.videoInterval); }; loadVideo = () => { clearInterval(this.state.videoInterval); }; playingVideo = () => { const interval = setInterval(this.captureVideoTime, 1000); this.setState({ videoInterval: interval }); };我不知道为什么 componentDidMount 调用了两次,因为它显示内存占用问题。
3 回答
月关宝盒
TA贡献1772条经验 获得超5个赞
我认为问题存在于使用 SingleVideoPlay 组件的父组件上。可能是那个父组件导致 SingleVideoPlay 组件渲染了不止一次。另外,你的代码有问题。
componentDidMount() {
this._Mounted = true;
if (this._Mounted) {
const videoId = this.props.match.params.id;
this.getVideoDetails(videoId);
}
}
在这里,无需检查 this._Mounted 是否已安装,因为它始终为真。
添加回答
举报
0/150
提交
取消