gpt4 book ai didi

reactjs - React : request to API trigger two times the then block, 请求发送了两次

转载 作者:行者123 更新时间:2023-12-05 09:31:18 25 4
gpt4 key购买 nike

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

输出:

第 1 页 ... 渲染

发送请求...

{data: "Hello there", status: 200, statusText: "", headers: {...}, config: {...}, ...}

{data: "Hello there", status: 200, statusText: "", headers: {...}, config: {...}, ...}


为什么会这样?我还检查了网络选项卡,请求都是 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;

最佳答案

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

关于reactjs - React : request to API trigger two times the then block, 请求发送了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68914256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com