首页 > 解决方案 > 通过数组和 API 调用进行异步映射时如何在 React 中设置状态

问题描述

我正在尝试在 React 中通过我的状态(收藏夹)映射()以从状态中的每个条目中获取数据。数据应存储在另一种状态、股票中,并显示在表格中。

Map() 通过状态和获取数据工作,我可以在控制台日志中看到日期。但它不会存储在状态中。

如何将数据添加到状态?

这是代码:

  // Calling the function on component mount
  useEffect(() => {
      tableFetch();
  }, []);

  const [favorites, setFavorites] = useState(["aapl", "arlv"]);
  const [stocks, setStocks] = useState([]);

    // fetch symbol data and stores it in stocks
      const tableFetch = () => {
        favorites.map( async (favorites) => {
          const data = await fetch(
                `https://cloud.iexapis.com/stable/stock/${favorites}/quote?token=${token}`
              );
          const stocksData = await data.json();
          console.log(stocksData)
          setStocks(stocksData);
        });
      }

标签: reactjsstatesetstate

解决方案


这里有几个问题。

  1. 当您在收到响应后进行 API 调用时,状态将被新数据覆盖,或者可能会发出范围可用性

建议: 2. 你为什么不进行多次API调用,当它们解决时,收集所有信息然后setState。

useEffect(() => {
    tableFetch();
  }, []);

  const tableFetch = async () => {
    // Note: the below code will create urls & make parallel calls
    let axiosFetch = favorites.reduce((axiosCalls, url) => {
      axiosCalls.push(axios.get(`https://reqres.in/api/users?page=${url}`));
      return axiosCalls;
    }, []);

    // Here promises will settle and will collect all the data.
    await axios
      .all(axiosFetch)
      .then((data) => {
        let dataCollected = data.reduce((dataCollected, response) => {
          dataCollected = dataCollected.concat(response.data.data);
          return dataCollected;
        }, []);
        // After collecting all the data we can set data into state at once.
        setStocks(dataCollected);
      })
      .catch((error) => {
        console.log("collect errors", error);
      });
  };

示例代码示例,您可以玩转

注意:我使用的是 Axios 库,同样的事情也可以使用 fetch 完成。


推荐阅读