簡體   English   中英

console.log() 在控制台上打印 undefined

[英]console.log() printing undefined on the console

我的申請者.js

import React, { useEffect, useState } from "react";
import "./Applicant.css";
import axios from "axios";
import Applicant from "./Applicant";
const URL = "http://localhost:5000/applicants";
const fetchHandler = async () => {
  return await axios.get(URL).then((res) => res.data);
};
const Applicants = () => {
  const [applicants, setApplicant] = useState();
  useEffect(() => {
    fetchHandler().then((data) => setApplicant(data.applicants));
  }, []);
  console.log(applicants);
  return (
    <div>
      <ul>
        {applicants &&
          applicants.map((applicant, i) => (
            <li key={i}>
              <Applicant applicant={applicant} />
            </li>
          ))}
      </ul>
    </div>
  );
};

export default Applicants;

在控制台中 output 是:未定義的申請者.js

控制台中沒有其他錯誤,只有這個。 我正在使用反應 v6

useEffect 與 [] 一起作為 compomentDidMount 工作(這意味着在沒有任何依賴的情況下傳遞)並且您正在嘗試在其運行之前打印 state 未定義

setState()在基於隊列的系統中異步運行。 因此,如果您要更新 state,此更新將堆積在系統隊列中。

但是,您可以檢查數據是否已加載

  const [applicants, setApplicant] = useState();
  useEffect(() => {
    fetchHandler().then((data) => 
       const newApplicants = data.applicants
       setApplicant(data.applicants));
       console.log(newApplicants) // returns data
       console.log(applicants) // returns undefined but in the final state it will contain the data
  }, []);

暫無
暫無

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

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