Javascript 使用Axios获取请求后,useState钩子阵列上的console.log会多次记录日志
我有这个反应组件Javascript 使用Axios获取请求后,useState钩子阵列上的console.log会多次记录日志,javascript,reactjs,react-native,axios,Javascript,Reactjs,React Native,Axios,我有这个反应组件 import React, { useState, useEffect } from 'react'; import axios from "axios"; import "../../css/driversStandings.css"; function DriversStandingsComponent() { const [data, setData] = useState([]); var row = 1;
import React, { useState, useEffect } from 'react';
import axios from "axios";
import "../../css/driversStandings.css";
function DriversStandingsComponent() {
const [data, setData] = useState([]);
var row = 1;
useEffect(() => {
axios.get("http://localhost:4000/api/standings").then(res => {
const driversChampionshipData = res.data[0].DriversChampionship
setData(driversChampionshipData);
console.log(data)
})
});
return (
//Here I return a mdbootstrap table, mapping the data array
)
}
export default DriversStandingsComponent;
我真的不明白为什么会发生这种情况,以及它是否会影响服务器性能
有解决这个问题的办法吗?我甚至不知道这是否是一个错误本身useEffect在每次组件重新加载时都被调用。您必须添加空的依赖项数组,这样只有在装入组件时useEffect才会调用,如下所示:
useEffect(() => {
axios.get("http://localhost:4000/api/standings").then(res => {
const driversChampionshipData = res.data[0].DriversChampionship
setData(driversChampionshipData);
console.log(data)
})
}, []);
每次组件重新渲染时都会调用useEffect。您必须添加空的依赖项数组,这样只有在装入组件时useEffect才会调用,如下所示:
useEffect(() => {
axios.get("http://localhost:4000/api/standings").then(res => {
const driversChampionshipData = res.data[0].DriversChampionship
setData(driversChampionshipData);
console.log(data)
})
}, []);
您可能已经设置了
,这将导致仅在开发中进行双重登录。但无论如何,在生产之前,你应该去掉你的控制台。日志。事实上,我已经设置了
。感谢我不知道的有用数据,您可能已经设置了
,这将导致仅在开发中重复登录。但无论如何,在生产之前,你应该去掉你的控制台。日志。事实上,我已经设置了
。感谢我不知道的有用数据支持此答案的文档:支持此答案的文档: