reactjs - 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;
解决方案
当您的应用程序被包装在<React.StrictMode>
您的组件中时,将在开发环境中呈现两次。这是用于错误/警告检测。严格模式将有意调用以下类组件函数两次:构造函数、render
方法和shouldComponentUpdate
方法。在文档中阅读有关严格模式的更多信息。
推荐阅读
- r - 无法上传最新的胶水包1.3.0
- r - 咕噜声,分组和过滤
- c - 在 qsort 中使用 strcmp() 比较字符串
- sql - 在 SQL 查询中使用一系列 excel 值作为条件
- php - 获取与 Woocommerce 订单项目相关的产品自定义字段
- amazon-web-services - 使用 Lambda 和 AWS Cognito 进行身份验证
- cross-compiling - 交叉编译 OpenSSL
- performance - 诊断 AWS Elastic Block Storage 性能
- reactjs - React.js 如何将数据从父组件传递到子组件
- eclipse-hono - Hono 命令和控制 API 未收到消息