为什么我的API请求被称为4次?
我正在研究一个提出API请求的项目,但是我的请求被称为4次,为什么会发生这种情况?
const [movies, setMovies] = useState([]);
const [searchTerm, setSearchTerm] = useState('')
useEffect(() => {
getMovies(FEATURED_API)
if (searchTerm) {
getMovies(SEARCH_API + searchTerm);
} else{
getMovies(FEATURED_API)
}
}, [searchTerm])
const getMovies = (API) => {
fetch(API)
.then((res) => res.json())
.then((data) => {
console.log(data)
setMovies(data.results)
})
}
const handleOnChange = (e) => {
setSearchTerm(e.target.value)
}```
I'm working on a project that makes an api request, but my request is being called 4 times, why is this happening?
const [movies, setMovies] = useState([]);
const [searchTerm, setSearchTerm] = useState('')
useEffect(() => {
getMovies(FEATURED_API)
if (searchTerm) {
getMovies(SEARCH_API + searchTerm);
} else{
getMovies(FEATURED_API)
}
}, [searchTerm])
const getMovies = (API) => {
fetch(API)
.then((res) => res.json())
.then((data) => {
console.log(data)
setMovies(data.results)
})
}
const handleOnChange = (e) => {
setSearchTerm(e.target.value)
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在您的代码中,您正在调用
getMovies(prainured_api)
在坐骑上两次(一个在之外的一个,另一个在 else 中)。另外两个调用可能是因为您启用了
strictmode
启用(默认为create> create-react-app-app
),并且您尚未注意到它。strictmode
在开发模式下两次安装组件,以帮助您以更轻松的方式检测代码中的问题。您可以检查此帖子评论具有更具描述性的概念。
In your code you are calling the
getMovies(FEATURED_API)
twice on mount (one outside the if cause and the other in the else).And the other two calls are probably because you have
StrictMode
enabled (it is enabled as default withcreate-react-app
) and you haven't noticed it.StrictMode
mounts your component twice in development mode to help you detect problems in your code in an easier way.You can check this post comment with a more descriptive concept of what StrictMode does.