我无法访问 DateList 函数中 sessionDates 数组中存储的数据
我无法访问 DateList 函数中 sessionDates 数组中存储的数据,
这是我的 index.js 中的代码,包括 api 调用
import React from "react";
import ReactDOM from "react-dom";
const availableDates = [];
const available = [];
const sessionDates = [];
function getDates(e){
getDate(apiUrl);
}
const getDate = async (apiUrl)=>{
const res = await fetch(apiUrl)
try {
const data = await res.json();
availableDates.push(data);
availableDates.map((datee) => {
datee.map((session) => {
sessionDates.push(session.date.slice(0, 10));
});
});
return sessionDates;
} catch(error) {
console.log("error", error);
}
}
window.addEventListener('load', getDates);
function DateList(){
return <section>{sessionDates[0]}</section>;
}
I can't access the data stored in my sessionDates array in my DateList function
this is the code from my index.js including the api call
import React from "react";
import ReactDOM from "react-dom";
const availableDates = [];
const available = [];
const sessionDates = [];
function getDates(e){
getDate(apiUrl);
}
const getDate = async (apiUrl)=>{
const res = await fetch(apiUrl)
try {
const data = await res.json();
availableDates.push(data);
availableDates.map((datee) => {
datee.map((session) => {
sessionDates.push(session.date.slice(0, 10));
});
});
return sessionDates;
} catch(error) {
console.log("error", error);
}
}
window.addEventListener('load', getDates);
function DateList(){
return <section>{sessionDates[0]}</section>;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您根据 API 调用设置
sessionDates
时,您的代码中没有任何内容会在sessionDates
更改时提示DateList
重新呈现。因此,它只会显示sessionDates
的初始值,其中sessionDates[0]
未定义。相反,我建议您使用
useEffect
挂钩触发您的 api 调用并使用useState
。While you are setting
sessionDates
based on the api call, there is nothing in your code that promptsDateList
to re-render whensessionDates
changes. As such, it will only display the initial value ofsessionDates
, for whichsessionDates[0]
is undefined.Instead, I recommend that you use the
useEffect
hook to trigger your api call and implementsessionDates
usinguseState
.