简体   繁体   English

无法将状态设置为 map 函数内的对象数组

[英]Not able to set state as array of objects inside map function

I am getting data from word press API then I structure the data inside the map function.我从 wordpress API 获取数据,然后在 map 函数中构建数据。 I am not able to set state as array of objects inside map function I get Arrays of different objects or Objects of different objects but not a single Array of Objects我无法将状态设置为 map 函数内的对象数组我得到了不同对象的数组或不同对象的对象但不是单个对象数组

  const rsp = response.data;

  const map = rsp && rsp.map(item => {
    let struct = {};
    let data = [];
    const id = item.id;
    const title = item.title['rendered'];
    const image = item['_embedded']['wp:featuredmedia'][0].source_url;
    const banner = item.ACF.banner_image.url;
    const products = item.ACF.celebrity_products;


    let store={
      id:id,
      title:title,
      image:image,
      banner:banner,
      products:products
    };


    setRes(prevState => {

      // struct['data'] =store;
      // data.push(store);
      return{ ...prevState,
      id: store.id,
      name: store.title,
      uri: store.image,
      banner: store.banner,
      products: store.products


  }})

  });

I think you'd want more something like :我想你会想要更多的东西:

const [items, setItems] = useState([])

rsp && setItems(rsp.map(item => ({
  id: item.id,
  name: item.title['rendered'],
  uri: item['_embedded']['wp:featuredmedia'][0].source_url,
  banner: item.ACF.banner_image.url,
  products: item.ACF.celebrity_products
})))

I think you didn't provide the complete story of you code.我认为您没有提供完整的代码故事。 but I think we can help.但我认为我们可以提供帮助。

if you intend to have the result of your processing as an array inside the map variable then you should've returned something inside it like如果您打算将处理结果作为 map 变量内的数组,那么您应该在其中返回一些内容,例如

let oddNumber = [ 1, 3, 5 ];
const map = oddNumber.map( oneOddNumber => { return oneOddNumber * 2; } );
// now map is [ 2, 6, 10 ]

or if you intend to save the array you want using setRes function then you should've done something like或者如果你打算使用setRes函数保存你想要的数组,那么你应该做类似的事情

setRes(prevState => ({ 
    ...prevState,
    theResultArray: [...prevState.theResultArray, { id: store.id, ..... } ]
}))

and now you state have the property name theResultArray which is an array of object which you've iterated on.现在您声明了属性名称theResultArray ,它是您迭代的对象数组。

hope you can provide more complete code so help can be more clear next time :D希望您能提供更完整的代码,以便下次帮助更清晰:D

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

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