首页 > 解决方案 > 我正在尝试显示从本地服务器获取的数据,但收到错误消息

问题描述

这是组件: 该组件应该显示从我的本地主机服务器获取的数据

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
}
]

标签: javascriptreactjsreact-hooks

解决方案


问题是res.json()异步的,因此您需要将它们与进一步的.then()调用链接起来 - 或使用async/await来避免大量.then()调用或创建回调地狱。

因此,请尝试以下操作 - 只需遵循您的代码片段:

useEffect(() => {
    fetch("http://localhost:5000/getjob")
      .then(res => res.json())
      .then(data => {
         setJobs(data);
      });
}, []);

我删除了错误处理只是为了看看如何使用fetchwith.json()所以不要忘记把它放回你的代码中。建议阅读使用 Fetch,您可以在其中找到上述解决方案的示例。

我希望这有帮助!


推荐阅读