简体   繁体   English

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

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

my applicants.js我的申请者.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;

In the console the output is: undefined applicants.js在控制台中 output 是:未定义的申请者.js

there is no other error in the console only this one.控制台中没有其他错误,只有这个。 i'm using react v6我正在使用反应 v6

useEffect is working as compomentDidMount with [] (that means passing without any dependency) and you are trying to print before its running at that time state is undefined useEffect 与 [] 一起作为 compomentDidMount 工作(这意味着在没有任何依赖的情况下传递)并且您正在尝试在其运行之前打印 state 未定义

setState() runs asynchronously in a queue based system. setState()在基于队列的系统中异步运行。 Therefore if you want to update a state, this update will be piled up on the system queue.因此,如果您要更新 state,此更新将堆积在系统队列中。

However, you can check if data has been loaded但是,您可以检查数据是否已加载

  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