首页 > 解决方案 > React:对API的请求触发两次然后阻塞,请求被发送两次

问题描述

我知道 API 调用不能放在 render 方法中,但这只是为了测试:我有下面的代码。当我将 fetchData 调用到渲染方法中时,“发送请求 ...”消息被打印一次,响应被打印两次!?

输出:

第 1 页 ... 渲染

发送请求 ...

{数据:“你好”,状态:200,状态文本:“”,标题:{...},配置:{...},...}

{数据:“你好”,状态:200,状态文本:“”,标题:{...},配置:{...},...}


为什么会发生这种情况?我还检查了网络选项卡,请求都是 GET 而不是与 CORS 相关的 OPTIONS。

同样在服务器上,GET 方法处理程序已执行两次。

import React from 'react';
const axios = require('axios').default;

class Page1 extends React.Component {

    // componentDidMount() {
    //     this.fetchData()
    // }

    fetchData() {
        console.log('Send request ...');
        axios.get('http://localhost:8080/api/hello/')
        .then(function (response) {
            console.log(response);
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    }


    render() {
        console.log('[Page 1] render called')
        this.fetchData();
        return (<h1>Hello from Page 1. </h1>);
    }
}
export default Page1;

标签: reactjsaxios

解决方案


当您的应用程序被包装在<React.StrictMode>您的组件中时,将在开发环境中呈现两次。这是用于错误/警告检测。严格模式将有意调用以下类组件函数两次:构造函数、render方法和shouldComponentUpdate方法。在文档中阅读有关严格模式的更多信息。


推荐阅读