React Fetch API 在頁面加載時被呼叫 2 次,我不知道這段代碼中缺少什么或我做錯了什么。我從早上就遇到了這個問題,非常感謝您提供的任何幫助。React Fetch API 在頁面加載時被呼叫 2 次,我不知道這段代碼中缺少什么或我做錯了什么。我從早上就面臨這個問題,我非常感謝你能提供的任何幫助。
import React, { useState, useEffect } from 'react'
import axios from 'axios';
import { Grid, Paper, TextField } from '@mui/material'
import PersonOutlineIcon from '@mui/icons-material/PersonOutline';
function FormApi() {
//Mui fileds and paper style
const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }
//Fetch data from api
const [userx, setUserx] = useState([{data:null,support:null}]);
const url = 'https://reqres.in/api/users/2';
useEffect(()=>{
//debugger
const fetchData = async () =>{
await axios.get(`${url}`)
.then((response) =>{
setUserx(response.data)
}).catch((error)=>{
console.log(error)
})
}
fetchData();
}
,[]);
return (
<Grid container spacing={2} style={paperStyle}>
<Grid align='center' >
<Paper elevation={20} >
<Grid align='center'>
<h2 style={{padding:'10px' ,background: "#000080", color: 'white' }}>
<PersonOutlineIcon large style={{fontSize:'80%'}} />User Details</h2>
</Grid>
<form>
<img style={{width:"20%"}} src={userx.data ? userx.data.avatar : ''}/>
<h1 style={{color:'#000080'}}>{userx.data ? userx.data.first_name : ''}
{userx.data ? userx.data.last_name : ''}</h1>
<Grid container >
<Grid item xs={6} >
<h2 style={{color:'white', background: "purple"}}>Contact Info</h2>
<TextField value={userx.data ? userx.data.id : ''} variant="standard"
/>
<TextField value={userx.data ? userx.data.email : ''}
variant="standard" />
</Grid>
<Grid item align='left' xs={6} style={{marginBottom:'40px'}}>
<h2 style={{color:'white', background: "purple"}}>Social Link</h2>
<TextField value={userx.support ? userx.support.url : ''}
variant="standard" />
<TextField value={userx.support ? userx.support.text : ''}
variant="standard" />
</Grid>
</Grid>
</form>
</Paper>
</Grid>
</Grid>
)
}enter code here
export default FormApi
uj5u.com熱心網友回復:
據我所知,這個問題是由 HTTP 客戶端發送 2 個請求引起的,一個到路由路徑“/”,另一個到“/favicon.ico”
進行此更改:
useEffect(()=>{
checkLocation();
//your code
,[]);
uj5u.com熱心網友回復:
經過一些修改后試試這個
函式 FormApi() {
//Mui fileds and paper style
const paperStyle = { padding: '50px ', width: 550, margin: '50px auto' }
//Fetch data from api
const [userx, setUserx] = useState([{data:null,support:null}]);
const url = 'https://reqres.in/api/users/2';
//debugger
const fetchData = async () =>{
await axios.get(`${url}`)
.then((response) =>{
setUserx(response.data)
}).catch((error)=>{
console.log(error)
})
}
useEffect(()=>{
fetchData();
}
,[]);
uj5u.com熱心網友回復:
這是React 18中的正常行為。它只會在開發環境和啟用 StrictMode 時完成,并且在您的生產構建中不會成為問題。
有點煩人,但沒什么好擔心的。有一個解決方法,您可以在此處的深入答案中了解更多資訊: React 18, useEffect is getting called two times on mount
uj5u.com熱心網友回復:
您可以使用 useRef 掛鉤處理它:
const renderAfterCalled = useRef(false);
useEffect(() => {
if (!renderAfterCalled.current) {
// your API call func
}
renderAfterCalled.current = true;
}, []);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/481600.html
標籤:javascript npm axios
