简体   繁体   English

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

[英]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) 显示了这个

Same Array used to display in html用于在 html 中显示的相同数组

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:这意味着如果再次调用useStaterender将只能获得一个新值:

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 值holidayPlansdateArray分配给本地常量(或变量,这无关紧要),并且每次渲染组件时都会分配这些值。 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.

相关问题 javascript 当我尝试使用数组时,它显示未定义 - javascript When I try to use a array ,it shows undefined 当我尝试在Google脚本中使用数组映射函数时出现语法错误。 为什么? - I get a syntax error when I try to use array map function in Google Scripts. Why? 我从 API 获取数组,但是当我尝试在表中显示它时它显示空数组(noob ReactJs) - I GET array from API but when i try show it in the table it show me empty array (noob ReactJs) 为什么当我尝试访问它的数组时,传递给第二个 function 的 object(包含一个数组)会给出一个空数组? - Why does the object (containing an array) passed to second function, give an empty array when I try to access its array? 为什么我会丢失存储在数组中的数据,这是 object 的一个字段 - Why do I lose data stored in an array, which is a field of an object when I try to access it by 当我尝试在组件上使用数组方法时,为什么我的数组变量未在我的组件中定义? - Why is my array variable undefined in my component when I try to use array methods on it? firestore:当我尝试按日期获取数据时,数组为空 - firestore: array empty when i try to get data by date 为什么我从涉及使用 Azure API 的 JavaScript 异步操作的 Promise.all 调用中得到“未定义”和空数组 []? - Why am I getting 'undefined' and empty array[] from a Promise.all call involving JavaScript async operations that use Azure APIs? 为什么当 function 数组不为空时我得到空响应? - Why I get an empty response when inside the function the array is not empty? 过滤器 function 显示一个空数组 - filter function shows an empty array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM