簡體   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?

用於將數據從 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);
    });
  };

那么,當我使用 Same (holidayPlans) 數組顯示 html 中的某些內容時,它顯示了值並正確顯示,但是當我在 function 中使用時,它顯示數組中沒有數據。

console.log(holidayPlans) 顯示了這個

用於在 html 中顯示的相同數組

這是一個挑戰:寫一個 JavaScript function useState這樣 console.log 輸出一個4然后一個5

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

無論你做什么,你永遠無法寫出這個 function,因為沒有外部 JavaScript function 將能夠設置thing變量的值; 那是因為外部 JavaScript 沒有辦法修改thing變量。 useState所能做的就是設置它自己的內部state 並更改它返回的內容。 愚蠢的例子在這里:

let hiddenState;
function useState(initialValue) {
  if (hiddenState === undefined) {
    hiddenState = initialValue;
  }
  const setState = value => {
    hiddenState = value;
  }
  return [hiddenState, setState];
}

這意味着如果再次調用useStaterender將只能獲得一個新值:

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

  [thing, setThing] = useState(4);
  console.log(thing); // 5
}

這本質上就是useState所做的,但是隱藏的 state 每個實例都是唯一的。 如您所見, setState被視為“異步”,因為 state 更改直到下一次渲染才會反映出來。 setState排隊重新渲染請求。 下次調用 render function 時,將再次調用useState ,並返回一個新值。

請注意,通過這些代碼修改,而不是我們在更新之前引用 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>;
}

如果你移動你的console.log(holidayPlans); 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);

發生這種情況是因為當您使用useState掛鈎時,您將 state 值holidayPlansdateArray分配給本地常量(或變量,這無關緊要),並且每次渲染組件時都會分配這些值。 這意味着組件中的常量值不會立即更新,但會反映在下一次渲染中,這將由您在getHolidayPlans中執行的 state 更新觸發。 這就是為什么如果您將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只是一個 function,它的主體在每個渲染周期執行。

基於此,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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM