React - api 数据在 ui 中不可见?

React - api data not visible in the ui?

因此,我正在尝试显示接下来几天的位置和天气,但我只是很难在 ui 中显示数据 - 我的反应很新,真的感谢任何意见

这是codesandbox

中的代码
import "./styles.css";

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


// goal : to display the weather shown every 3 hours for the next days 

export default function App() {
  const [data, setData] = useState(null);  
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);


  const api = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=-16.516667&lon=-68.166667&altitude=4150";
  useEffect(() => {
   if (!api) return;
    setLoading(true);
    fetch(api)
      .then((response) => response.json())
      .then(setData)
      .then(() => setLoading(false))
      .catch(setError);
  }, []);

  
console.log(data)

  if (loading) return <h1>Loading...</h1>;
  if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
  if (!data) return null;

  if (data) {
    return ( 
      <div className="Layout">

<p> Cordinates here </p>

<p>{data.geometry.coordinates[0]}</p>

{data.geometry.coordinates.map((i) => (
  <ul  key={i.geometry}>
  <li>{i.coordinates}</li>
</ul>
))}
<p> Timeseries here </p>
  
{data.properties.timeseries.map((i) => (
  <ul key={i.timeseries}>
  <li>{i.timeseries}</li>
</ul>
))}

    </div>
    );
  }
  return <div> Could not get the data</div>;
}

您处理 map 方法的方式存在一些问题。编辑如下


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


// goal : to display the weather shown every 3 hours for the next days 

export default function App() {
  const [data, setData] = useState(null);  
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);


  const api = "https://api.met.no/weatherapi/locationforecast/2.0/complete?lat=-16.516667&lon=-68.166667&altitude=4150";
  useEffect(() => {
   if (!api) return;
    setLoading(true);
    fetch(api)
      .then((response) => response.json())
      .then(setData)
      .then(() => setLoading(false))
      .catch(setError);
  }, []);

  
console.log(data)

  if (loading) return <h1>Loading...</h1>;
  if (error) return <pre>{JSON.stringify(error, null, 2)}</pre>;
  if (!data) return null;

  if (data) {
    return ( 
      <div className="Layout">

<p> Cordinates here </p>

<p>{data.geometry.coordinates[0]}</p>

{data.geometry.coordinates.map((i) => (
  <ul  key={i.geometry}>
  <li>{i}</li>
</ul>
))}
<p> Timeseries here </p>
  
{data.properties.timeseries.map((j) => (
  <ul key={j.timeseries}>
  <li>{j.time}</li>
</ul>
))}

    </div>
    );
  }
  return <div> Could not get the data</div>;
}

Codesandbox here