如何在 React 组件中使用 Promise.all 结果?

How do I use Promise.all results in a React component?

我需要弄清楚如何从我的 public 文件夹中获取多个 GeoJSON 文件并在 React 组件中呈现坐标。这是相关的代码片段:

export const CoordinatesComponent = () => {
  const [data, setData]: any = useState([]);
  const [isLoading, setLoading] = useState(true);
    
  useEffect(() => {
    let isMounted = true;
    const dataPromises = Promise.all([
      fetch("data/boundary.json", {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      }),
      fetch("data/neighborhoods.json", {
        headers: {
          "Content-Type": "application/json",
          Accept: "application/json",
        },
      }),
    ])
    .then((response) => response.map((a) => a.json()));
    
    const setState = () => {
      if (isMounted) {
        dataPromises.then((a) => setData(a));
        setLoading(false);
      }
      return () => {
        isMounted = false;
      };
    };
    
    setState();
    
  }, []);
    
  if (isLoading) {
    return <div>Loading...</div>;
  }
  return (
    <div>{data}</div> // Just a placeholder.  This array of geoJson objects would be fed into another component
  );
};

虽然我可以通过单个获取操作来完成此操作,但我很难让它与 Promise.all 一起使用。当我 console.log 数据变量时,我看到了一个未定义对象数组。任何帮助将不胜感激!

问题出在以下 then 块中。由于您现在有一系列承诺,再次从响应中获得 JSON 将是相同的问题,您需要 return res.json()Promise.all 调用中的承诺。

then((response) => response.map((a) => a.json()));

应该更正如下。

then((responses) => Promise.all(responses.map((res) => res.json())));