Javascript React在从api获取时生成无限错误

Javascript React在从api获取时生成无限错误,javascript,reactjs,Javascript,Reactjs,我是React.js新手,我正在尝试从api获取状态。但是当我这样做的时候,在api中的json代码更改之后或者经过一段时间之后,我会得到无限的错误:TypeError:Failed to fetch和Posts.js:10 gethttp://localhost:3000/data 网络::错误连接被拒绝 我的财务总监: import React, { useState } from 'react'; import Post from './Post'; import axios from '

我是React.js新手,我正在尝试从api获取状态。但是当我这样做的时候,在api中的json代码更改之后或者经过一段时间之后,我会得到无限的错误:
TypeError:Failed to fetch
Posts.js:10 gethttp://localhost:3000/data 网络::错误连接被拒绝

我的财务总监:

import React, { useState } from 'react';
import Post from './Post';
import axios from 'axios';


const Posts = () => {
    const [posts, setPosts] = useState([]);


    fetch("http://localhost:3000/data")
    .then(res => res.json())
    .then(
      (result) => {
        setPosts((prev) => prev = result);
      }
    )
    .catch((error) => {
        console.log(error);
      });

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;
import React,{useState}来自“React”;
从“./Post”导入Post;
从“axios”导入axios;
const Posts=()=>{
const[posts,setPosts]=useState([]);
取回(“http://localhost:3000/data")
.then(res=>res.json())
.那么(
(结果)=>{
设置柱((prev)=>prev=结果);
}
)
.catch((错误)=>{
console.log(错误);
});
返回(
posts.map((post,index)=>(
))
);
}
导出默认职位;

首先需要在函数中包装api调用。否则,它将在每次组件渲染时重新渲染:

import React, { useState,useEffect } from 'react';
import Post from './Post';
import axios from 'axios';


const Posts = () => {
    const [posts, setPosts] = useState([]);
    
    useEffect(() => {
    fetchPost();
     },[])

    const fetchPost = () => {
        fetch("http://localhost:3000/data")
        .then(res => res.json())
        .then(
        (result) => {
          setPosts((prev) => prev = result);
         }
        )
        .catch((error) => {
         console.log(error);
        });
     }

    return (
        posts.map((post, index) => (
            <Post name={post.name} content={post.content} key={index}/>
        ))
    );
}
export default Posts;


此错误通常出现在后端不工作时

听起来像是本地主机服务器的问题,但出现无限错误是正常的吗?在我的API控制台中,当我在Web站点上时,我收到无限请求。您也应该只在初始呈现时获取—将
fetch
放在
useffect(fn,[])
中,它可以工作,但是如果react只从该API获取一次数据,那么状态点是什么呢?这意味着就像第一次加载组件时获取API一样。如果它是一次性数据,则只能更新。不频繁的操作将更改任何数据,因此不需要新的获取。如果在useffect中传递空数组[]。它的工作原理类似于基于类的componentDidMount。但是您在依赖项中传递了[variable]。它是一种工作组件,每当变量值发生变化时,它都会在哪里运行。哦,我看到了,所以你必须选择是只需要一次更新,还是通过传递变量来更新?是的,正确。如果你不想每次都打电话。传递空数组。如果要在某些变量更新时调用。然后传递该变量。它将只为变量change+first time renderAnytime:-)运行,如果在only run first time中给出空数组,则基本上更新了上述注释
Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED