为什么componentdidmount调用了两次

问题描述

我在 componentDidMount 中有React Component从服务器获取数据。问题是 componentDidMount 调用了两次,API调用了两次。我有一个视图增量API,例如youtube视频视图在数据库中由于两次API调用增加了两次。

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 });
    };
    
    getVideoDetails = async (videoId) => {
        const video = await getVideo(videoId);

        if (video.status === 200) {
            let response = video.data;
            if (this.props.userId)
                if (response.user._id === this.props.userId._id)
                    this.props.videoEditUrl(`/video/edit/${response.media._id}`);
            this.setState({
                relatedVideos: response.videos.docs,video: response.media,user: response.user
            });
            this.checkIsFollowing();
            this.updateVideoStat(response.media._id);
        }
    };
    updateVideoStat = async (id) => videoView(id);
    checkIsFollowing = async () => {
        const { userId } = this.props;
        const { video } = this.state;
        if (userId && video) {
            const response = await isFollow({
                follower: userId._id,following: video._id
            });
            if (response) {
                this.setState({ following: response.following });
            }
        }
    };
    addOrRemoveFollowing = async () => {
        this.checkIsFollowing();
        const { following,video } = this.state;
        const { userId } = this.props;
        if (userId) {
            if (following) {
                const response = await removeFollow({
                    follower: userId._id,following: video._id
                });
                this.setState({ following: false });
            } else {
                const response = await addFollow({
                    follower: userId._id,following: video._id
                });
                this.setState({ following: true });
            }
        }
    };

    submitCommentHandler = async (event) => {
        const { userId } = this.props;
        event.preventDefault();
        if (userId) {
            const result = await saveComment({
                mediaId: this.state.video._id,parentId: '0',userID: userId._id,userName: userId.username,comment: this.state.commentInput.value
            });
            console.log(result);
            if (result.status === 200) {
                this.getVideoComments();
                this.setState({ commentInput: { value: '',error: false } });
            }
        }
    };

    render() {
        const { autoplay,relatedVideos,video,user,comments,commentInput,following,tab } = this.state;
        const { userId } = this.props;
        return (
            <div className="container-fluid">
        
            some coponents
            </div>
        );
    }
}

const mapStatetoProps = (state) => ({
    userId: state.auth.user
});

export default connect(mapStatetoProps,{ videoEditUrl })(SingleVideoPlay);

我不知道为什么componentDidMount调用了两次,否则显示内存泄漏问题。

如何修复它。

解决方法

我认为使用SingleVideoPlay组件的父组件存在此问题。父组件可能导致SingleVideoPlay组件渲染了多次。 另外,您的代码也有问题。

    componentDidMount() {
        this._Mounted = true;
        if (this._Mounted) {
            const videoId = this.props.match.params.id;
            this.getVideoDetails(videoId);
        }
    }

这里,无需检查this._Mounted,因为它始终为真。