【问题标题】:Handling a Promise object in React JS在 React JS 中处理 Promise 对象
【发布时间】:2022-11-04 00:56:58
【问题描述】:

我的localhost:8000/ 端口上有一个 API 端点;此端点仅返回以下对象{"message": "hello"}

我想使用我的 React JS 脚本来获取这个对象。我的脚本添加在下面。

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

const App = () => {
    const [message, setMessage] = useState("");
    const getHomePageData = async () => {
        const requestOptions = {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        };
        const response = await fetch("/", requestOptions)
        if (!response.ok) {
            console.log("Error in fetching the data!");
        } else {
            console.log("Data fetched correctly!");
        }
        return await response.json();
    };
    const data = getHomePageData();
    console.log(data);
    return(
        <center><h1>Hello, world!</h1></center>
    );
}
export default App;

获取数据似乎工作正常,因为我在控制台中收到以下日志:Data fetched correctly! 因此我认为我的后端一切正常。但是在下一行我收到以下错误消息:Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.

如何修复我的代码以获取 .json() 数据?

【问题讨论】:

  • 使App fn 异步并像这样调用const data = getHomePageData(); const data = await getHomePageData();
  • @Joel,我仍然遇到同样的错误:(
  • 而不是return await response.json()const text = await response.text(); console.log(text); return JSON.parse(text);。检查控制台。我敢打赌,你没有从你的端点得到你所期望的。
  • 您还可以检查网络选项卡,过滤 XHR 请求并检查响应
  • fetch("/", 可能会返回 /console.log(response) 的 html 以确保您得到想要的响应

标签: javascript reactjs


【解决方案1】:

尝试使用useEffect

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

const App = () => {
    const [message, setMessage] = useState("");
    useEffect(() => {
      const getHomePageData = async () => {
        try {
          const requestOptions = {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            }
          };
          const response = await fetch("/", requestOptions)
          const data = await response.json();
          setMessage(data.message);
        } catch (error) {
          console.log(error);
        }
      };
      getHomePageData();
    }, []);
    return(
        <center><h1>Hello, world!</h1></center>
    );
}
export default App;

【讨论】:

  • 我的意思是,你没有错:OP 绝对应该包含在 useEffect 中。话虽如此,我严重怀疑这是他们看到的错误的原因。
  • data 在登录时仍然是 promise ...
  • 这没有用;(
  • const data = getHomePageData(); 应该是 const data = await getHomePageData();
  • @Joel 不,它应该在没有等待的情况下工作
猜你喜欢
  • 2016-04-13
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 2018-08-11
相关资源
最近更新 更多