为什么我的API请求被称为4次?

发布于 2025-02-11 05:17:05 字数 610 浏览 1 评论 0原文

我正在研究一个提出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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

卷耳 2025-02-18 05:17:05

在您的代码中,您正在调用getMovies(prainured_api)在坐骑上两次(一个之外的一个,另一个在 else 中)。

useEffect(() => {

 getMovies(FEATURED_API) // first call

 if (searchTerm) {
   getMovies(SEARCH_API + searchTerm);
 } else{
  getMovies(FEATURED_API) // second call because searchTerm is an empty string
 }
}, [searchTerm])

另外两个调用可能是因为您启用了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).

useEffect(() => {

 getMovies(FEATURED_API) // first call

 if (searchTerm) {
   getMovies(SEARCH_API + searchTerm);
 } else{
  getMovies(FEATURED_API) // second call because searchTerm is an empty string
 }
}, [searchTerm])

And the other two calls are probably because you have StrictMode enabled (it is enabled as default with create-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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文