javascript - 检查了无数次都无法弄清楚我的错误在哪里 : Uncaught TypeError: Cannot read properties of undefined (reading 'lat' )

标签 javascript reactjs react-hooks openweathermap

我一直在尝试使用 OpenWeatherMap API 来学习编码,并遇到了控制台中弹出的一系列 TypeError 问题。我的假设是我的程序在完成获取之前尝试使用来自 API 的数据,但我已将获取函数设置为等到收到响应后将它们添加到相应的状态,并尝试了许多解决方案。我已在下面添加了我的 App.js 代码(已提交 API key ):

function App() {
  // initialize location as UWS (no actual reason)
  const [location, setLocation] = useState("10024");

  // GeoCoder API data to feed into the main weather API
  const [inputData, setInputData] = useState();

  // Main weather API data to feed to UI
  const [apiData, setApiData] = useState();

  // GeoCoder API used for fetching latitude & longitude
  const geoCoder = `http://api.openweathermap.org/geo/1.0/zip?zip=${location},US&appid=${API__KEY}`;

  // Main weather API used for feeding data to the UI (based on lat & lon from geoCoder API)
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${inputData.lat}&lon=${inputData.lon}&appid=${API__KEY}&units=imperial`;

  // Use user-submitted zip code to fetch latitude & longitude from geoCoder API
  const getInputData = async () => {
    const res = await fetch(geoCoder);
    const jsonRes = await res.json();
    setInputData(jsonRes);
  };

  // Use Zip code from geoCoder API to fetch data from main weather API
  const getApiData = async () => {
    const res = await fetch(url);
    const jsonRes = await res.json();
    setApiData(jsonRes);
  };

  // Initialize website with data
  useEffect(() => {
    getInputData();
  }, []);

  return (
    <div className="container">
      <Title />
      <Search
        location={location}
        setLocation={setLocation}
        getInputData={getInputData}
        getApiData={getApiData}
      />
      <Pinpoint apiData={apiData} />
      <ForecastPreview apiData={apiData} />
      <ForecastDetails apiData={apiData} />
    </div>
  );
}

其他上下文:apiData 状态作为 props 传递给子组件,并用于根据 apiData 中存储的数据在屏幕上渲染数据。

控制台中有多个错误,就像我在问题标题中包含的错误一样,可能都源于同一问题。

过去三个小时我一直无法弄清楚这一点。非常感谢任何和所有的帮助。

最佳答案

也许可以尝试以下步骤来生成正确的 url,且不会出现错误:

  1. inputData 提供具有正确数据模型的初始值
  2. inputData 未准备好时,为 url 提供后备值

以下实例将使用公共(public) API,因此不需要 key ,并且如果切换到项目 API,它也应该可以工作。

示例:(codesandbox 上的简化现场演示)

inputData 需要正确的数据模型让 url 读取其属性:

// GeoCoder API data to feed into the main weather API
const [inputData, setInputData] = useState({ lat: null, lon: null });
inputData 被获取但尚未准备好时,

url 需要一个后备值(这里使用 null 但它可以是任何东西,取决于它将如何使用):

// Main weather API used for feeding data to the UI (based on lat & lon from geoCoder API)
const url =
  inputData?.lat && inputData?.lon
    ? `https://api.openweathermap.org/data/2.5/weather?lat=${inputData.lat}&lon=${inputData.lon}&appid=API__KEY&units=imperial`
    : null;

可选:数据获取函数可以在useEffect内部创建,因此不需要将其添加到依赖数组中。

// Initialize website with data
useEffect(() => {
  const initInputData = async () => {
    if (!geoCoder) return;
    const res = await fetch(geoCoder);
    if (!res.ok) throw new Error("fetch failed");
    const jsonRes = await res.json();
    setInputData(jsonRes);
  };
  initInputData().catch((error) => console.error(error));
}, [geoCoder]);

可能还有其他问题需要解决,但希望这至少可以帮助生成没有错误的正确网址。

关于javascript - 检查了无数次都无法弄清楚我的错误在哪里 : Uncaught TypeError: Cannot read properties of undefined (reading 'lat' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74696904/

相关文章:

javascript - 对一个数组进行排序并使其他两个数组保持同步

javascript - Chrome 上 window.postMessage 的问题

javascript - 重置 useState 的初始状态

javascript - React 组件的状态从构造函数更改为 componentDidMount 不会影响渲染?

javascript - 移动设备上的 React useEffect Hook 未清除 setTimeout

javascript - 使用 React hooks 显示来自 jsonplaceholder api 的数据

reactjs - 在对象上 react 和 typescript useState

javascript - 从 codeigniter Controller 发送电子邮件后无法在 jquery 中获得响应

javascript - 如何在网页中多次播放同一个音频文件?

javascript - 带有 React Router 的 ReactJS - Chrome 上的奇怪路由行为