繁体   English   中英

当我尝试获取它的特定元素时,React 数组返回未定义

[英]React array returns undefined when i try to get specific element of it

我尝试进行 2 次数据获取,一次获取所有产品,然后完成我 map 所有产品并分别获取每个产品并将它们放入数组中。 当我尝试打印结果时,我不明白的行为发生了。 如果我 console.log 整个数组,一切正常,但如果我尝试用单个数组项来做,它返回未定义。 不要问我为什么要单独取所有产品。

这是代码。


import React, { useEffect, useState } from "react";
import axios from "axios";

export const Stackoverflow1 = () => {
  const [data, setData] = useState("");
  const [singleData, setSingleData] = useState("");
  const [finished, setFinished] = useState(false);
  const API = `${process.env.REACT_APP_SERVER_URL}/api/products`;
  useEffect(() => {
    const fetchData = () => {
      axios.get(API).then((response) => {
        setData(response.data);
        setFinished(true);
      });
    };

    fetchData();
  }, []);

  useEffect(() => {
    if (finished) {
      let list = [];

      data &&
        data.map(async (item) => {
          const API = `${process.env.REACT_APP_SERVER_URL}/api/products/${item.id}`;
          axios.get(API).then((response) => {
            list.push(response.data);
          });
        });
      setSingleData(list);
    }
  }, [finished, data]);

  return (
    <div>
      {data &&
        singleData &&
        data.map((item, index) => (
          <div>
            {item.name}
            {console.log("inside code without index", singleData)}
            {console.log("inside code with index", singleData[0])}
          </div>
        ))}
    </div>
  );
};

//Console logs:

// inside html without index :
// []
// 0: {id: 381, name: 'Akvariumas 30l', description: 'Akvariumas 30l', price: 25.99, image_name: '16491014443.aquael-glossy-100-juodas.jpeg', …}
// 1: {id: 391, name: 'Akvariumas 20l', description: 'akvariumas 20l', price: 12, image_name: '16491031283.aquarium3.jpeg', …}
// 2: {id: 401, name: 'Akvariumas 30l', description: 'Akvariumas 30l', price: 150, image_name: '16491063713.aquarium4.jpeg', …}
// length: 3
// [[Prototype]]: Array(0)

//inside html with index undefined

你应该使用 Promise.all 来等待所有的承诺:

useEffect(() => {
    if (finished && data) {
      let list = [];
      Promise.all(data.map(async (item) => {
        const API = `${process.env.REACT_APP_SERVER_URL}/api/products/${item.id}`;
        const response = await axios.get(API);
        list.push(response.data)
      })).then(() => setSingleData(list))
    }
  }, [finished, data]);

暂无
暂无

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

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