我知道 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;
<React.StrictMode>
? - Keith Brewster