简体   繁体   English

如何在单个阵列中推送多个 json(响应)?

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

i need data in this form [{..},{..},{..}].我需要这种形式的数据[{..},{..},{..}]. i create blank array const arr = [] and all json data push in this Array.我创建空白数组const arr = []并将所有 json 数据推送到此数组中。 arr.push(data) the output is [{..}] [{..}] but i need all object in one array. arr.push(data) output 是[{..}] [{..}]但我需要一个阵列中的所有 object。 how to fix it?如何解决?

  // 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 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', …}

You could use the spread operator to push objects to an array.您可以使用扩展运算符将对象推送到数组。 Refer to the sample code参考示例代码

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;

Hi @Shreyash Kolhe you can try something like this.嗨@Shreyash Kolhe,您可以尝试这样的事情。

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

with useState you will have the data and a setter function to set data.使用useState您将拥有数据和一个设置器 function 来设置数据。 In your Axios call, you can set the data as below.在您的 Axios 调用中,您可以如下设置数据。

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

The preData will hold the previous data which you current state data. preData将保存您当前 state 数据的先前数据。 This will append the new data with the old data you have in your state.这将 append 新数据与您在 state 中的旧数据。 Please share the code next time it will help the community to help you out more effectively.下次请分享代码,它将帮助社区更有效地帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM