The fetch request is running twice. I don’t know why.

huangapple go评论138阅读模式
英文:

The fetch request is running twice. I don't know why

问题

import React, { useState, useEffect } from 'react'

export function UseStateExample() {
  const [resourceType, setResourceType] = useState(null)

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
      .then(response => response.json())
      .then(json => console.log(json))
  }, [resourceType])

  return (
    <>
      <div>
        <button onClick={() => setResourceType('posts')}>Posts</button>
        <button onClick={() => setResourceType('users')}>Users</button>
        <button onClick={() => setResourceType('comments')}>Comments</button>
      </div>
      <h1>{resourceType}</h1>
    </>
  )
}

显然,useEffect 钩子应该只运行一次。但是当我重新加载页面后检查控制台,我发现 fetch 请求运行了两次。

英文:
import React, {useState, useEffect} from &#39;react&#39;

export function UseStateExample() { // named export, need to use the same name everywhere nad {} when importing/exporting.
  const [resourceType, setResourceType] = useState(null)

  useEffect(() =&gt; {
    fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
      .then(response =&gt; response.json())
      .then(json =&gt; console.log(json))
  }, [resourceType])

  // useEffect(() =&gt; {s
  //   console.log(&#39;On Mount, since it is an empty array&#39;)
  // }, [])

  return (
    &lt;&gt;
      &lt;div&gt;
        &lt;button onClick={() =&gt; setResourceType(&#39;posts&#39;)}&gt;Posts&lt;/button&gt;
        &lt;button onClick={() =&gt; setResourceType(&#39;users&#39;)}&gt;Users&lt;/button&gt;
        &lt;button onClick={() =&gt; setResourceType(&#39;comments&#39;)}&gt;Comments&lt;/button&gt;
      &lt;/div&gt;
      &lt;h1&gt;{resourceType}&lt;/h1&gt;
    &lt;/&gt;
  )
}

Apparently, the useEffect hook should run only once. But when I check the console after reloading the page, I see that the fetch request runs twice.

答案1

得分: 1

I think this is happening because React.StrictMode is enabled in your react application. See this answer.
To disable StrictMode go to your index.js file and remove or comment next 2 lines:

  // &lt;React.StrictMode&gt; remove or comment this tag
       &lt;App /&gt;
  // &lt;/React.StrictMode&gt; and this tag

and re-run your application.

英文:

I think this is happening because React.StrictMode is enabled in your react application. See this answer.
To disable StrictMode go to your index.js file and remove or comment next 2 lines:

  // &lt;React.StrictMode&gt; remove or comment this tag
       &lt;App /&gt;
  // &lt;/React.StrictMode&gt; and this tag

and re-run your application.

huangapple
  • 本文由 发表于 2023年3月7日 03:32:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75655075.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定