javascript - 我正在尝试显示从本地服务器获取的数据,但收到错误消息
问题描述
这是组件: 该组件应该显示从我的本地主机服务器获取的数据
import React, {useState, useEffect} from 'react';
function FindJob(){
const [jobs, setJobs] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
fetch("http://localhost:5000/getjob")
.then(res => {
const results = res.json();
setJobs(results);
},
(error) => setError(error)
)
}, []);
if(error){
console.log(error);
} else {
console.log(jobs);
return <div>
{jobs.map(job => (
<h2>{job.post}</h2>
))}
</div>
}
}
export default FindJob;
这是我在运行 REACT应用程序时遇到的错误 ,但我已经像 react.org 中关于 ajax 调用的示例一样编写了它
×
Unhandled Rejection (TypeError): jobs.map is not a function
FindJob
C:/Users/user/Desktop/ben/jobconnect/jc-front/src/components/findjob.jsx:23
20 | console.log(error);
21 | } else {
22 | console.log(jobs);
> 23 | return <div>
| ^ 24 | {jobs.map(job => (
25 | <h2>{job.post}</h2>
26 | ))}
View compiled
▶ 17 stack frames were collapsed.
(anonymous function)
C:/Users/user/Desktop/ben/jobconnect/jc-front/src/components/findjob.jsx:12
9 | fetch("http://localhost:5000/getjob")
10 | .then(res => {
11 | const results = res.json();
> 12 | setJobs(results);
| ^ 13 |
14 | },
15 | (error) => setError(error)
View compiled
此数据尚未显示,但我可以 console.log 它
这是从我的本地服务器获取的数据:
[
{
"_id": "5ed8f1494a9a902b38986dba",
"post": "general manager",
"organization": "oracle",
"description": "someone to oversee day to day operaetions",
"__v": 0
},
{
"_id": "5edf615e274cdb3c94847e5a",
"post": "developer",
"organization": "andela",
"description": "full stack developer",
"__v": 0
},
{
"_id": "5ee3a541e29e9e0be44cd370",
"__v": 0
}
]
解决方案
问题是res.json()
异步的,因此您需要将它们与进一步的.then()
调用链接起来 - 或使用async
/await
来避免大量.then()
调用或创建回调地狱。
因此,请尝试以下操作 - 只需遵循您的代码片段:
useEffect(() => {
fetch("http://localhost:5000/getjob")
.then(res => res.json())
.then(data => {
setJobs(data);
});
}, []);
我删除了错误处理只是为了看看如何使用fetch
with.json()
所以不要忘记把它放回你的代码中。建议阅读使用 Fetch,您可以在其中找到上述解决方案的示例。
我希望这有帮助!
推荐阅读
- php - PHP 联系表单 - 基于选定表单值的动态电子邮件列表
- oracle - Oracle XE (11g) 分页失败。原因:偏移获取失败并出现错误:命令未正确结束
- c# - Entity Core 2.0.3 例外:必须是可简化节点
- c# - 与 C# 泛型、T、抽象有点混淆?
- java - 一本名著证实java字符串是一个数组?
- jquery - jQuery将一个值传递给它的目标页面
- anylogic - 如何获取特定节点上特定代理(来自 MHL)所花费的时间?
- android - Gradle 版本规范:使用带有 API lvl 27 的 mancj/MaterialSearchBar?
- python-3.x - Python joblib 无法并行填充列表
- c - 将 unsigned char 解析为 int 指针后的段错误