[英]Data from API call are stored in a Array but when i try to use that array in a function for further use it shows that array is empty . why?
React code for storing Data from API to an Array and Using the same Array's event_date value for further use.用于将数据从 API 存储到数组并使用相同数组的 event_date 值以供进一步使用的React代码。
export const UpcomingHolidays = (props: UpcomingHolidaysProps) => {
const [holidayPlans, setHolidayPlans] = useState([]);
const [dateArray, setDate] = useState([]);
useEffect(() => {
getHolidayPlans();
}, []);
const getHolidayPlans = async () => {
const holidayResp = await PortalHolidayService.getInstance().getHolidayPlans();
if (holidayResp) {
setCities(() => holidayResp.cityModule);
setHolidayPlans(() => holidayResp.holidayModule);
setDate(() => holidayResp.holidayModule);
}
let today = new Date();
console.log(holidayPlans);
holidayPlans.filter((date) => {
const eventDate = new Date(date.event_date);
console.log(eventDate);
});
};
So what the thing is when i use the Same (holidayPlans) array to display some contents in html it shows the values and displays properly but when i use inside a function it shows there is no data inside the array.那么,当我使用 Same (holidayPlans) 数组显示 html 中的某些内容时,它显示了值并正确显示,但是当我在 function 中使用时,它显示数组中没有数据。
console.log(holidayPlans) shows this console.log(holidayPlans) 显示了这个
Here's a challenge: write a JavaScript function useState
such that the console.log outputs a 4
and then a 5
:这是一个挑战:写一个 JavaScript function
useState
这样 console.log 输出一个4
然后一个5
:
function render() {
let [thing, setThing] = useState(4);
console.log(thing); // 4
setThing(5);
console.log(thing); // 5
}
No matter what you do, you'll never be able to write this function, because no external JavaScript function will be able to set the value of the thing
variable;无论你做什么,你永远无法写出这个 function,因为没有外部 JavaScript function 将能够设置
thing
变量的值; that's because an external JavaScript has no way to modify the thing
variable.那是因为外部 JavaScript 没有办法修改
thing
变量。 All useState
would be able to do is set its own internal state and change what it returns. useState
所能做的就是设置它自己的内部state 并更改它返回的内容。 Silly example here:愚蠢的例子在这里:
let hiddenState;
function useState(initialValue) {
if (hiddenState === undefined) {
hiddenState = initialValue;
}
const setState = value => {
hiddenState = value;
}
return [hiddenState, setState];
}
That means render
will only be able to get a new value if useState
is called again:这意味着如果再次调用
useState
, render
将只能获得一个新值:
function render() {
let [thing, setThing] = useState(4);
console.log(thing); // 4
setThing(5);
[thing, setThing] = useState(4);
console.log(thing); // 5
}
This is essentially what useState
does but in a way where the hidden state is unique per instance.这本质上就是
useState
所做的,但是隐藏的 state 每个实例都是唯一的。 As you can see, setState
is to be considered "asynchronous" in that state changes aren't reflected until the next render .如您所见,
setState
被视为“异步”,因为 state 更改直到下一次渲染才会反映出来。 setState
queues up a re-render request. setState
排队重新渲染请求。 The next time your render function is called, useState
will be called again, and it will return a new value.下次调用 render function 时,将再次调用
useState
,并返回一个新值。
Notice with these code modifications, rather than us referencing the state variable before it has updated, we can still reference your response object to get the data:请注意,通过这些代码修改,而不是我们在更新之前引用 state 变量,我们仍然可以引用您的响应 object 来获取数据:
export const UpcomingHolidays = (props: UpcomingHolidaysProps) => {
// On the first rendering of `UpcomingHolidays`, holidayPlans will be [].
// After setHolidayPlans is called, a re-render will be queued, and this
// UpcomingHolidays function will be called again. When useState is called
// the second time, it will have the value passed into setHolidayPlans.
const [holidayPlans, setHolidayPlans] = useState([]);
// Same for dateArray.
const [dateArray, setDate] = useState([]);
useEffect(() => {
getHolidayPlans();
}, []);
async function getHolidayPlans() {
const holidayResp = await PortalHolidayService.getInstance().getHolidayPlans();
if (!holidayResp) {
return;
}
// These will flag the component as needing to re-render after the effect
// completes. They do not change the local variables; they update the
// internal data of the useState hooks so that the next time those useState
// calls occur, they'll return new values.
setCities(holidayResp.cityModule);
setHolidayPlans(holidayResp.holidayModule);
setDate(holidayResp.holidayModule.map(date => new Date(date.event_date));
// If you want to log here, don't reference state, which hasn't updated yet.
// Either store response data as variables or reference the response itself.
console.log('Holidays are', holidayResp.holidayModule);
}
return <div>Your content</div>;
}
If you move your console.log(holidayPlans);
如果你移动你的
console.log(holidayPlans);
out of getHolidayPlans
function, you get an updated value.从
getHolidayPlans
function 中,您将获得更新后的值。
export const UpcomingHolidays = (props: UpcomingHolidaysProps) => {
const [holidayPlans, setHolidayPlans] = useState([]);
const [dateArray, setDate] = useState([]);
useEffect(() => {
const getHolidayPlans = async () => {
const holidayResp = await PortalHolidayService.getInstance().getHolidayPlans();
if (holidayResp) {
setCities(holidayResp.cityModule);
setHolidayPlans(holidayResp.holidayModule); // you may filter data here
setDate(holidayResp.holidayModule);
}
};
getHolidayPlans();
}, []);
console.log(holidayPlans);
This happens because when you use the useState
hook, you are assigning the state values holidayPlans
and dateArray
to local constants (or variables, this does not matter), and these values are assigned each time the component is rendered.发生这种情况是因为当您使用
useState
挂钩时,您将 state 值holidayPlans
和dateArray
分配给本地常量(或变量,这无关紧要),并且每次渲染组件时都会分配这些值。 This means that the constant value in your component will not get updated immediately, but it will be reflected in the next render, which will be triggered by the state updates that you do within getHolidayPlans
.这意味着组件中的常量值不会立即更新,但会反映在下一次渲染中,这将由您在
getHolidayPlans
中执行的 state 更新触发。 This is why, if you place the console.log()
call outside getHolidayPlans
, the value is printed properly.这就是为什么如果您将
console.log()
调用放在getHolidayPlans
之外,该值将被正确打印。
export const UpcomingHolidays = (props: UpcomingHolidaysProps) => {
const [holidayPlans, setHolidayPlans] = useState([]);
const [dateArray, setDate] = useState([]);
useEffect(() => {
getHolidayPlans();
}, []);
const getHolidayPlans = async () => {
const holidayResp = await PortalHolidayService.getInstance().getHolidayPlans();
if (holidayResp) {
setCities(() => holidayResp.cityModule);
setHolidayPlans(() => holidayResp.holidayModule);
setDate(() => holidayResp.holidayModule);
}
// ...
};
console.log(holidayPlans);
Basically this is what happens:基本上是这样的:
First render
|
V
useEffect executes getHolidayPlans()
|
V
getHolidayPlans() performs state changes,
triggering a new render cycle
|
V
Second render,
which will have new state values
It is important to notice that in the end UpcomingHolidays
is just a function, and its body is executed on each render cycle.重要的是要注意,最后
UpcomingHolidays
只是一个 function,它的主体在每个渲染周期执行。
Based on this, the recommended way to go is to use constant/variables local to the caller function ( getHolidayPlans()
) instead of using the state constant/variables immediately after their respective setState
function has been called, because they are updated after the completion of the function that it was called in.基于此,go 的推荐方法是使用调用方 function (
getHolidayPlans()
) 本地的常量/变量,而不是在调用各自的setState
function 后立即使用 state 常量/变量,因为它们在完成后更新它被调用的 function。
export const UpcomingHolidays = (props: UpcomingHolidaysProps) => {
const [holidayPlans, setHolidayPlans] = useState([]);
const [dateArray, setDate] = useState([]);
useEffect(() => {
getHolidayPlans();
}, []);
const getHolidayPlans = async () => {
const holidayResp = await PortalHolidayService.getInstance().getHolidayPlans();
const holidayPlansLocal = holidayResp.holidayModule;
if (holidayResp) {
setCities(() => holidayResp.cityModule);
setHolidayPlans(() => holidayResp.holidayModule);
setDate(() => holidayResp.holidayModule);
}
let today = new Date();
console.log(holidayPlansLocal);
holidayPlansLocal.filter((date) => {
const eventDate = new Date(date.event_date);
console.log(eventDate);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.