簡體   English   中英

如何在單個陣列中推送多個 json(響應)?

[英]How to push multiple json (response ) in single array?

我需要這種形式的數據[{..},{..},{..}]. 我創建空白數組const arr = []並將所有 json 數據推送到此數組中。 arr.push(data) output 是[{..}] [{..}]但我需要一個陣列中的所有 object。 如何解決?

  // const arr = []
  const [data, setData] = useState()
  // const [arrData, setArrData] = useState()
  useEffect(() => {
  const data = JSON.parse(localStorage.getItem('Cart'));
  if (!data) {
    console.log('go to empty Cart')
  } else {
    data.map(async (v) => {
      try {
        axios.get(`/cart/${v}`)
        .then(res=>setData(res.data))
        .catch(e=>{console.log(e)})
      } catch (e) {
        console.log(e);
        navigator('/Login');
      }
    })
  }    
  }, [])
  // arr.push(data)
  console.log(data)

Output

{_id: '61ed1af4ac1a79e2c4f45937', title: 'Birthday bannner Template Tranding Template', DiscountPrice: 149, OriginalPrice: 199, category: 'Birthday Banner', …}


{_id: '61ec1b25689c12b75aa2929a', title: 'Birthday Banner Marathi Template', DiscountPrice: 149, OriginalPrice: 200, category: 'Birthday Banner', …}

您可以使用擴展運算符將對象推送到數組。 參考示例代碼

import React, { useState } from 'react';
import './style.css';

const App = () => {
  const [data, setData] = useState([]);
  const [count, setCount] = useState(1);

  const handleClick = () => {
    // your response from the API call
    const dataObj = {
      id: count,
      name: 'some name',
      title: 'some title',
    };
    setCount((prevCount) => prevCount + 1);
    setData([...data, dataObj]); // should work fine with your implementation as well
  };
  return (
    <div>
      <button onClick={handleClick}>Click to add</button>
      {data.map((item) => (
        <div key={item.id}>
          {item.id} {item.name}
        </div>
      ))}
    </div>
  );
};
export default App;

嗨@Shreyash Kolhe,您可以嘗試這樣的事情。

const [data, setData] = useState([]);

使用useState您將擁有數據和一個設置器 function 來設置數據。 在您的 Axios 調用中,您可以如下設置數據。

setData(preData => [...preData, res.data]);

preData將保存您當前 state 數據的先前數據。 這將 append 新數據與您在 state 中的舊數據。 下次請分享代碼,它將幫助社區更有效地幫助您。

暫無
暫無

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

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