在FC组件中,我有以下代码:
我只想在组件挂载时调用API并记录信息
控制台日志会对空数组调用两次,并对设置相同值的情况调用两次。
import * as React from"react";
import Header from"../components/Header";
import Search from"../components/Search";
import Categories from"../components/Categories";
import Carousel from"../components/Carousel";
import CarouselItem from"../components/CarouselItem";
import Footer from"../components/Footer";
import "../assets/styles/App.scss";
const App = () => {
const [videos, setVideos] = React.useState([]);
React.useEffect(() => {
fetch("http://localhost:3000/initalState")
.then((response) => response.json())
.then((data) => setVideos(data));
}, []);
console.log(videos);
return (
<div className="App">
<Header></Header>
<Search></Search>
<Categories title="Mi Lista">
<Carousel>
<CarouselItem />
<CarouselItem />
<CarouselItem />
<CarouselItem />
<CarouselItem />
</Carousel>
</Categories>
<Categories title="Tendencias">
<Carousel>
<CarouselItem />
<CarouselItem />
</Carousel>
</Categories>
<Categories title="Originales de Platzi Video">
<Carousel>
<CarouselItem />
</Carousel>
</Categories>
<Footer />
</div>
);
};
export default App;
然而,我得到了以下的输出:
在 useEffect 中进行调用:
React.useEffect(() => {
fetch("http://localhost:3000/initalState")
.then((response) => response.json())
.then((data) => {
setVideos(data);
console.log(videos);
});
}, []);
返回一个空数组。
<App/>
组件被挂载。可能已经是这样了,但首先清除明显的问题会有所帮助。 - charlietfl