30秒到達戰(zhàn)場
2023-01-06 09:26:03
我在componentDidMount中有 React Component從服務(wù)器獲取數(shù)據(jù)。問題是componentDidMount被調(diào)用了兩次,API 也被調(diào)用了兩次。由于兩次 API 調(diào)用,我有一個視圖增量 API,例如 youtube 視頻視圖在數(shù)據(jù)庫中增加了兩次。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 調(diào)用了兩次,因為它顯示內(nèi)存占用問題。
3 回答

月關(guān)寶盒
TA貢獻1772條經(jīng)驗 獲得超5個贊
我認為問題存在于使用 SingleVideoPlay 組件的父組件上??赡苁悄莻€父組件導(dǎo)致 SingleVideoPlay 組件渲染了不止一次。另外,你的代碼有問題。
componentDidMount() {
this._Mounted = true;
if (this._Mounted) {
const videoId = this.props.match.params.id;
this.getVideoDetails(videoId);
}
}
在這里,無需檢查 this._Mounted 是否已安裝,因為它始終為真。

湖上湖
TA貢獻2003條經(jīng)驗 獲得超2個贊
1.通過npm i jquery安裝jQuery
從'jquery'導(dǎo)入$
在導(dǎo)出命令之后或放在文件末尾創(chuàng)建您的函數(shù)或 jwuery 代碼
添加回答
舉報
0/150
提交
取消