简体   繁体   English

React Fetch API 在页面加载时被调用 2 次

[英]React Fetch API Being Called 2 Times on page load

React Fetch API Being Called 2 Times on page load, I don't know what is missing in this code or what I am doing wrong. React Fetch API 在页面加载时被调用 2 次,我不知道这段代码中缺少什么或我做错了什么。 I have faced this problem from the morning, I really appreciate any help you can provide.我从早上就遇到了这个问题,非常感谢您提供的任何帮助。 React Fetch API Being Called 2 Times on page load, I don't know what is missing in this code or what I am doing wrong. React Fetch API 在页面加载时被调用 2 次,我不知道这段代码中缺少什么或我做错了什么。 I face this problem from the morning, I really appreciate any help you can provide.我从早上就面临这个问题,我非常感谢你能提供的任何帮助。

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

This is normal behaviour in React 18 .这是React 18中的正常行为。 It will only be done on development environments and when StrictMode is enabled and will not be a problem in your production Build.它只会在开发环境和启用 StrictMode 时完成,并且不会成为您的生产构建中的问题。

A bit annoying, but nothing really to worry about.有点烦人,但没什么好担心的。 There is a workaround which you can learn more about in a in-depth answer here: React 18, useEffect is getting called two times on mount有一个解决方法,您可以在此处的深入答案中了解更多信息: React 18, useEffect is getting called two times on mount

as much as I know, this issue is caused by the HTTTP client sending 2 request, one to the route path "/" and the other to "/favicon.ico"据我所知,这个问题是由 HTTP 客户端发送 2 个请求引起的,一个到路由路径“/”,另一个到“/favicon.ico”

make this change :进行此更改:

useEffect(()=>{ checkLocation(); //your code ,[]); useEffect(()=>{ checkLocation(); //your code ,[]);

after some revision try this经过一些修改后试试这个

function FormApi() {函数 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();
      }

    ,[]);

You can handle it with useRef hook:您可以使用 useRef 挂钩处理它:

const renderAfterCalled = useRef(false);

useEffect(() => {
    if (!renderAfterCalled.current) {
      // your API call func
    }

    renderAfterCalled.current = true;
}, []);

It's because React renders components 2 times in the development environment.这是因为 React 在开发环境中渲染组件 2 次。 To avoid this, you can comment out the <React.StrictMode> tag in index.js file.为避免这种情况,您可以注释掉index.js文件中的<React.StrictMode>标记。

Rendering twice will only appear in the development environment and StrictMode has many benefits for development:渲染两次只会出现在开发环境中,StrictMode 对开发有很多好处:

  • Identifying components with unsafe lifecycles识别具有不安全生命周期的组件
  • Warning about legacy string ref API usage关于旧字符串 ref API 使用的警告
  • Warning about deprecated findDOMNode usage关于不推荐使用 findDOMNode 的警告
  • Detecting unexpected side effects检测意外的副作用
  • Detecting legacy context API检测遗留上下文 API
  • Ensuring reusable state确保可重复使用 state

So it's better to keep the <React.StrictMode> tag if it doesn't affect your normal development work.所以最好保留<React.StrictMode>标签,如果它不影响你正常的开发工作。

See also: React StrictMode另请参阅:反应 StrictMode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM