簡體   English   中英

React 條件渲染的問題

[英]Problem with conditional rendering with React

我真的沒有錯誤,但我沒有得到想要的結果。 我有一個 Flask API 作為我的后端。 它返回 JSON 數據,然后將此數據傳遞給 React 前端,以在某些操作(例如單擊按鈕)后顯示。

Flask 后端工作正常,數據正在發送到 React 前端,我可以使用console.log(data)在控制台中查看它。

問題是我嘗試做一些事情來做到這一點,以便在從 API 獲取數據時,我希望顯示諸如“正在加載...”之類的消息。

這是我在這方面所做的。

const [data, setData] = useState([{}])

useEffect(() =>{
  fetch("/details").then(
    res => res.json()
  ).then(
    data => {
      setData(data)
      console.log(data)
    }
  )
}, [])

console.log(data)確實在控制台中顯示了我的 JSON 響應。

然后我這樣做是為了顯示。

return (
  <div>
    ...
    <div>
      {(typeof data.members === 'undefined') ? (
        <p>Loading...</p>
      ) : (
        data.members.map((member, i) => (
          <p key={i}>{member}</p>
        ))
      )}
    </div>
  </div>
);

這應該在獲取數據時顯示“正在加載...”,然后顯示數據。 但它一直顯示“正在加載...”,即使我的數據已被提取並且從未顯示。

我嘗試了 emrich 所說的並得到了這個錯誤TypeError: Cannot read properties of undefined (reading 'map')

App
D:/React/Candetect/src/App.jsx:32
  29 | <FileList files={files} removeFile={removeFile} />
  30 | <div>
  31 | {(data.length === 0) ? (
> 32 |   <p>Loading...</p>
     | ^  33 | ) : (
  34 |   data.members.map((member, i) => (
  35 |     <p key={i}>{member}</p>

D:/React/Candetect/src/App.jsx:15
  12 |   res => res.json()
  13 | ).then(
  14 |   data => {
> 15 |     setData(data)
     | ^  16 |     console.log(data)
  17 |   }
  18 | )

這是來自后端的對象

{
    "Information": [
        {
            "college_name": null,
            "company_names": [
                "Marathwada Mitra Mandal’s College of Engineering"
            ],
            "degree": [
                "B.E. IN COMPUTER ENGINEERING"
            ],
            "designation": [
                "Machine Learning",
                "TECHNICAL CONTENT WRITER",
                "Schlumberger\nDATA ENGINEER"
            ],
            "email": "omkarpathak27@gmail.com",
            "experience": [
                "Schlumberger",
                "DATA ENGINEER",
                "July 2018 - Present",
                "• Responsible for implementing and managing an end-to-end CI/CD Pipeline with custom validations for Informatica migrations which",
                "Pune, Maharashtra, India",
                "brought migration time to 1.5 hours from 9 hours without any manual intervention",
                "• Enhancing, auditing and maintaining custom data ingestion framework that ingest around 1TB of data each day to over 70 business",
                "units",
                "• Working with L3 developer team to ensure the discussed Scrum PBI’s are delivered on time for data ingestions",
                "• Planning and Executing QA and Production Release Cycle activities",
                "Truso",
                "FULL STACK DEVELOPER INTERN",
                "• Created RESTful apis",
                "• Tried my hands on Angular 5/6",
                "• Was responsible for Django backend development",
                "Pune, Maharashtra, India",
                "June 2018 - July 2018",
                "Propeluss",
                "DATA ENGINEERING INTERN",
                "• Wrote various automation scripts to scrape data from various websites.",
                "• Applied Natural Language Processing to articles scraped from the internet to extract different entities in these articles using entity",
                "Pune, Maharashtra, India",
                "October 2017 - January 2018",
                "extraction algorithms and applying Machine Learning to classify these articles.",
                "• Also applied KNN with LSA for extracting relevant tags for various startups based on their works.",
                "GeeksForGeeks",
                "TECHNICAL CONTENT WRITER",
                "• Published 4 articles for the topics such as Data Structures and Algorithms and Python",
                "Pune, Maharashtra, India",
                "July 2017 - September 2017",
                "Softtestlab Technologies",
                "WEB DEVELOPER INTERN",
                "• Was responsible for creating an internal project for the company using PHP and Laravel for testing purposes",
                "• Worked on a live project for creating closure reports using PHP and Excel"
            ],
            "mobile_number": "8087996634",
            "name": "Omkar Pathak",
            "no_of_pages": 3,
            "skills": [
                "Python",
                "Cloud",
                "Github",
                "Django",
                "Writing",
                "Unix",
                "Algorithms",
                "C",
                "Windows",
                "Training",
                "C++",
                "Flask",
                "Scrum",
                "Testing",
                "Reports",
                "Programming",
                "Operating systems",
                "Automation",
                "Engineering",
                "Html",
                "Css",
                "Analytics",
                "Opencv",
                "Content",
                "Excel",
                "Mysql",
                "Migration",
                "Api",
                "Parser",
                "Machine learning",
                "System",
                "Php",
                "Apis",
                "Auditing",
                "Technical",
                "Photography",
                "Shell",
                "Linux",
                "Security",
                "Website",
                "Javascript"
            ],
            "total_experience": 4.5
        }
    ]
} 

首先,您將data狀態的初始值設置為數組,但將其用作對象。 ( data.members )

如果來自 API 的數據是對象而不是數組,則需要將其設置為對象。

const [data, setData] = useState({})

然后你可以檢查對象是否已經設置,你可以通過對象鍵的長度來檢查

  return (
<div>
...
  <div>
  {Object.values(data).length ? (
    <p>Loading...</p>
  ) : (
    data.members.map((member, i) => (
      <p key={i}>{member}</p>
    ))
  )}
</div>
</div>

);

我會像這樣編輯代碼:

const [data, setData] = useState([])

    useEffect(() =>{
      fetch("/details").then(
        res => res.json()
      ).then(
        data => {
          setData(data.Information)
          console.log(data.Information)
        }
      )
    }, [])
(
    <div>
    ...
      <div>
      {(data.length === 0) ? (
        <p>Loading...</p>
      ) : (
        data.map((member, i) => (
          <p key={i}>{member.college_name}</p>
        ))
      )}
    </div>
    </div>
  );

很可能,在設置狀態后成員仍然未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM