React:请求API触发两次then块,请求被发送两次。

3

我知道 API 调用不能放在 render 方法中,但这只是为了测试:

当我将 fetchData 方法调用放入 render 方法中时,“发送请求…” 消息会打印一次,而响应则会打印两次!

输出:

第1页…正在渲染

发送请求…

{data:“你好”,状态:200,状态文本:“”,标头:{…},配置:{…},…}

{data:“你好”,状态: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;

1
你的应用程序是否包含了 <React.StrictMode> - Keith Brewster
@KeithBrewster 是的先生,您能解释一下原因吗? - Manolis P.
当然,我刚刚发了一个解释的答案! - Keith Brewster
1个回答

13

当你的应用程序在<React.StrictMode>中包裹时,你的组件将在开发环境下渲染两次。这是为了进行错误/警告检测。严格模式将有意地执行以下类组件函数两次:构造函数、render方法和shouldComponentUpdate方法。了解更多关于严格模式的信息,请阅读文档


好的,但为什么“发送请求...”只打印一次?我感到困惑。 - Manolis P.
2
他们实际上在第二次渲染期间有意劫持了 console.log。该更改的 PR 在此处:https://github.com/facebook/react/pull/18547。这是为了减少警告被双重打印时的混淆,但当您看到网络请求两次触发时仍然很困惑。 - Keith Brewster
谢谢你,Keith!当然,我对第二个请求感到困惑。有趣。再次感谢!我可以问一下为什么我看不到向我的后端API发出OPTIONS请求? - Manolis P.
不幸的是,我不确定为什么它没有发送OPTIONS请求,很抱歉。 - Keith Brewster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接