[英]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.