繁体   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