簡體   English   中英

使用 initalstate 更新反應鈎子中的 state

[英]update state in react hooks with initalstate

嘿,我有以下數據來自 api

0: {uuid: "a087b443-7af9-4464-8fd1-fb487fc60f66", name: "abc 19",}
1: {uuid: "baeb9282-84e9-4a72-b4e1-3a0ca6db7020", name: "abc 9", }

基本上它是一個數組。 現在我有這樣的初始數據

[
    { id: 1, storeName: "Store First", toAdd: true },
  ]

現在我想使用setState hook將來自api的數據推送到初始State。

這就是我所做的。

我使用 useEffect 調用 api。function 在 useEffect 之外聲明。在 function 中,我嘗試過類似這樣的推送數據。

0: {id: 1, storeName: "Store First", toAdd: true}
1: (2) [{…}, {…}]
2: (2) [{…}, {…}]

以下是我使用的代碼

 const [list, setList] = useState([
    { id: 1, storeName: "Store First", toAdd: true },
  ]);


const getdata = async () => {
   
    const { response } = await api.getdata(); // This give the following response
     =========
     0: {uuid: "a087b443-7af9-4464-8fd1-fb487fc60f66", name: "abc 19",}
     1: {uuid: "baeb9282-84e9-4a72-b4e1-3a0ca6db7020", name: "abc 9", }
     =========
     ////

    setStoreList((prevstate) => [...prevstate, response]); //This set the following 
    =========
    0: {id: 1, storeName: "Store First", toAdd: true}
    1: (2) [{…}, {…}]
    2: (2) [{…}, {…}]
    =========
  };

    //Use Effect to call the function
     useEffect(() => {
        getdata();
      }, []);

我到底想要什么

0: {id: 1, storeName: "Store First", toAdd: true}
1: {uuid: "a087b443-7af9-4464-8fd1-fb487fc60f66", name: "abc 19",}
2: {uuid: "baeb9282-84e9-4a72-b4e1-3a0ca6db7020", name: "abc 9", }

對象數組,以便我可以 map 結束。

我認為您的問題是您沒有傳播響應數組,請嘗試替換:

setStoreList((prevstate) => [...prevstate, response]); //This set the following  

setStoreList((prevstate) => [...prevstate, ...response]); //This set the following

由於您沒有傳播,因此每次鈎子運行時,它都會 append 響應數組到prevState

您可以在這里通過兩種方式 go:-

使用連接:-

setStoreList((prevstate) => prevState.concat(response)) ;

concat幫助您加入prevStateresponse數組並獲得一個新數組。

使用傳播:-

setStoreList((prevstate) => [...prevstate, ...response]) ;

擴展運算符讓我們將所有可迭代的內容擴展到位,這樣您就可以正確地為prevState執行此操作,但忘記為response執行此操作,它也是一個array ,因此是一個可迭代的。

ES6: setStoreList((prev) => [...prev, ...res])
或者基本上: setStoreList((prev) => prev.concat(res))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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