Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/464.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 来自API调用的数据存储在一个数组中,但当我试图在函数中使用该数组以供进一步使用时,它显示该数组为空。为什么?_Javascript_Reactjs_React Tsx - Fatal编程技术网

Javascript 来自API调用的数据存储在一个数组中,但当我试图在函数中使用该数组以供进一步使用时,它显示该数组为空。为什么?

Javascript 来自API调用的数据存储在一个数组中,但当我试图在函数中使用该数组以供进一步使用时,它显示该数组为空。为什么?,javascript,reactjs,react-tsx,Javascript,Reactjs,React Tsx,React用于将数据从API存储到数组的代码,并使用同一数组的事件日期值进一步使用 export const UpcomingHolidays = (props: UpcomingHolidaysProps) => { const [holidayPlans, setHolidayPlans] = useState([]); const [dateArray, setDate] = useState([]); useEffect(() => { getHoli

React用于将数据从API存储到数组的代码,并使用同一数组的事件日期值进一步使用

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);
    });
  };
所以,当我使用相同的(holidayPlans)数组以html格式显示某些内容时,它会显示值并正确显示,但当我在函数中使用时,它会显示数组中没有数据


如果移动
控制台.log(度假计划)
getHolidayPlans
函数中,您将获得一个更新的值

export const UpcomingHolidays=(道具:UpcomingHolidaysProps)=>{
const[holidayPlans,setHolidayPlans]=useState([]);
const[dateArray,setDate]=useState([]);
useffect(()=>{
const getHolidayPlans=async()=>{
const holidayResp=等待PortalHolidayService.getInstance().getHolidayPlans();
国际单项体育联合会(度假区){
设置城市(度假城市模块);
setHolidayPlans(holidayResp.holidayModule);//您可以在此处筛选数据
设置日期(holidayResp.holidayModule);
}
};
获取度假计划();
}, []);
控制台日志(度假计划);

这里有一个挑战:编写一个JavaScript函数
useState
,这样console.log会输出一个
4
,然后输出一个
5

function render() {
  let [thing, setThing] = useState(4);
  console.log(thing); // 4
  setThing(5);
  console.log(thing); // 5
}
无论你做什么,你都无法编写这个函数,因为没有外部JavaScript函数能够设置
thing
变量的值;这是因为外部JavaScript无法修改
thing
变量。所有
useState
能够做的就是设置自己的内部状态和更改它返回的内容。下面是一个愚蠢的示例:

let hiddenState;
function useState(initialValue) {
  if (hiddenState === undefined) {
    hiddenState = initialValue;
  }
  const setState = value => {
    hiddenState = value;
  }
  return [hiddenState, setState];
}
这意味着只有在再次调用
useState
时,
render
才能获取新值:

function render() {
  let [thing, setThing] = useState(4);
  console.log(thing); // 4
  setThing(5);

  [thing, setThing] = useState(4);
  console.log(thing); // 5
}
这本质上就是
useState
所做的,但是在某种程度上,每个实例的隐藏状态都是唯一的。正如您所看到的,
setState
被认为是“异步的”在这种情况下,只有在下次渲染时才会反映更改。
setState
将重新渲染请求排队。下次调用渲染函数时,将再次调用
useState
,并返回一个新值

请注意,通过这些代码修改,我们仍然可以引用您的响应对象来获取数据,而不是在状态变量更新之前引用它:

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>;
}
export const UpcomingHolidays=(道具:UpcomingHolidaysProps)=>{
//在第一次呈现“UpcomingHolidays”时,度假计划将为[]。
//调用setHolidayPlans后,重新渲染将排队,并且
//当调用useState时,将再次调用UpcomingHolidays函数
//第二次,它将把值传递给setHolidayPlans。
const[holidayPlans,setHolidayPlans]=useState([]);
//dateArray也是如此。
const[dateArray,setDate]=useState([]);
useffect(()=>{
获取度假计划();
}, []);
异步函数getHolidayPlans(){
const holidayResp=等待PortalHolidayService.getInstance().getHolidayPlans();
如果(!holidayResp){
返回;
}
//这些会将组件标记为需要在效果后重新渲染
//完成。它们不更改局部变量,而是更新
//useState钩子的内部数据,以便下次这些useState
//调用发生时,它们将返回新值。
设置城市(度假城市模块);
设置HolidayPlans(holidayResp.holidayModule);
setDate(holidayResp.holidayModule.map(日期=>新日期(日期.事件\日期));
//如果要在此处登录,请不要引用尚未更新的状态。
//将响应数据存储为变量或引用响应本身。
console.log('Holidays is',holidayResp.holidayModule);
}
返回您的内容;
}

发生这种情况的原因是,当您使用
useState
钩子时,您正在将状态值
holidayPlans
dateArray
分配给本地常量(或变量,这无关紧要),并且每次呈现组件时都会指定这些值。这意味着组件中的常量值不会立即更新,但它将反映在下一次呈现中,这将由您在
getHolidayPlans
中执行的状态更新触发。如果放置
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);
基本上是这样的:

             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
重要的是要注意,最后,
UpcomingHolidays
只是一个函数,它的主体在每个渲染周期中执行

基于此,建议使用调用者函数的本地常量/变量(
getHolidayPlans()
)而不是在调用各自的
setState
函数后立即使用状态常量/变量,因为它们是在调用函数完成后更新的

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);
    });
  };

半真半假。这将在组件的第一次渲染时记录
[]
,并在效果完成后重新渲染(
UpdateHolidays
称为第二次),然后第二次的
console.log
将有更新的值。是的,兄弟,它发生在第一次渲染时,显示了emptyI是react的初学者,所以理解这个概念很混乱。Jacob兄弟,你能不能用更简单的方式解释一下你在我的代码中做了哪些更改?我想清楚地理解。@Ramarvind:看看这个更新的代码是否清晰多谢兄弟,真的