javascript - React 从 api 获取时产生无限错误
问题描述
我是 React.js 的新手,我正在尝试从 api 获取到 state 。但是当我这样做时,在从 api 更改 json 代码后或一段时间后,我会收到无限错误:TypeError: Failed to fetch
和Posts.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;
解决方案
首先你需要在函数中包装 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
当您的后端不工作时,通常会出现此错误
推荐阅读
- powershell - 如何在字符编码、输入和输出流、引用和转义方面稳健地调用 PowerShell CLI?
- c# - 在日志文件中显示相关数据
- json - 我正在使用滚动视图来显示我正在通过 JASON 文件解析的数据,但是我想显示图像本身而不是图像 url
- json - 如何在 Laravel Blade 中对 json 响应进行分页
- amazon-web-services - 尝试传递动态变量时,值不是 Object 的成员
- apache-kafka - 为什么kafka消费者轮询经纪人?
- oop - 在这个类图中违反了哪条 SOLID 原则
- excel - Excel VBA:出错时转到值指向的行号
- tensorflow - PyTorch 是否有用于批处理规范的后向矩参数?
- google-sheets - 如何从范围更新时创建一个下拉列表?