首页 > 解决方案 > React 从 api 获取时产生无限错误

问题描述

我是 React.js 的新手,我正在尝试从 api 获取到 state 。但是当我这样做时,在从 api 更改 json 代码后或一段时间后,我会收到无限错误:TypeError: Failed to fetchPosts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED.

我的帖子控制器:

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;

标签: javascriptreactjs

解决方案


首先你需要在函数中包装 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 而不是将空数组作为依赖项传递。否则,您希望在 useEffect([] <- here) 中运行 fetchApi 的变量。

Posts.js:10 GET http://localhost:3000/data net::ERR_CONNECTION_REFUSED

当您的后端不工作时,通常会出现此错误


推荐阅读