英文:
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 'react'
export function UseStateExample() { // named export, need to use the same name everywhere nad {} when importing/exporting.
const [resourceType, setResourceType] = useState(null)
useEffect(() => {
fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
.then(response => response.json())
.then(json => console.log(json))
}, [resourceType])
// useEffect(() => {s
// console.log('On Mount, since it is an empty array')
// }, [])
return (
<>
<div>
<button onClick={() => setResourceType('posts')}>Posts</button>
<button onClick={() => setResourceType('users')}>Users</button>
<button onClick={() => setResourceType('comments')}>Comments</button>
</div>
<h1>{resourceType}</h1>
</>
)
}
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:
// <React.StrictMode> remove or comment this tag
<App />
// </React.StrictMode> 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:
// <React.StrictMode> remove or comment this tag
<App />
// </React.StrictMode> and this tag
and re-run your application.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论