为什么 componentdidmount 调用了两次

我在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 调用了两次,因为它显示内存占用问题。


30秒到达战场
浏览 747回答 3
3回答

大话西游666

多次componentDidMount调用可能是由于<React.StrictMode>在您的组件周围使用而引起的。删除它后,双重调用就消失了。这是旨在帮助检测意外副作用的行为。您可以在文档中阅读更多相关信息。它只发生在开发环境中,而在生产环境中componentDidMount即使使用<React.StrictMode>.这是用 React 18.1.0 测试的

月关宝盒

我认为问题存在于使用 SingleVideoPlay 组件的父组件上。可能是那个父组件导致 SingleVideoPlay 组件渲染了不止一次。另外,你的代码有问题。&nbsp; &nbsp; componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; this._Mounted = true;&nbsp; &nbsp; &nbsp; &nbsp; if (this._Mounted) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const videoId = this.props.match.params.id;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.getVideoDetails(videoId);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }在这里,无需检查 this._Mounted 是否已安装,因为它始终为真。

湖上湖

1.通过npm i jquery安装jQuery从'jquery'导入$在导出命令之后或放在文件末尾创建您的函数或 jwuery 代码
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript