【问题标题】:Fetching Data using custom hook on React使用 React 上的自定义钩子获取数据
【发布时间】:2022-01-07 23:32:51
【问题描述】:

我正在使用 vercel 进行部署,但我不知道如何设置环境变量,所以我想尝试使用 fetch("/data.json") 的方法。我也有用于获取数据的自定义钩子。 但这不起作用,我什至看不到我本地的数据。 data.json 文件直接位于 /public 文件夹中。有人可以帮我吗?

useFetch.js

import { useState, useEffect } from "react";

export const useFetch = (url, method = "GET") => {
  const [data, setData] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const [error, setError] = useState(null);
  const [options, setOptions] = useState(null);

  const postData = (postData) => {
    setOptions({
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(postData),
    });
  };

  useEffect(() => {
    const controller = new AbortController();
    const fetchData = async (fetchOptions) => {
      setIsPending(true);

      try {
        const res = await fetch(url, {
          ...fetchOptions,
          signal: controller.signal,
        });
        if (!res.ok) {
          throw new Error(res.statusText);
        }
        const json = await res.json();

        setIsPending(false);
        setData(json);
        setError(null);
      } catch (err) {
        if (err.name === "AbortError") {
          console.log("the fetch was aborted");
        } else {
          setIsPending(false);
          setError("Could not fetch the data");
        }
      }
    };
    if (method === "GET") {
      fetchData();
    }
    if (method === "POST" && options) {
      fetchData(options);
    }
    return () => {
      controller.abort();
    };
  }, [url, options, method]);
  return { data, isPending, error, postData };
};

TaskList.js

import { useFetch } from "../hooks/useFetch";

import { useFrequency } from "../hooks/useFrequency";

//images
import Dot from "../assets/icon-ellipsis.svg";

// styles
import "./TaskList.scss";

export default function TaskList() {
  // const [url, setUrl] = useState("http://localhost:3000/stats");
  const { data: stats, isPending, error } = useFetch("/data.json");

  const { frequency } = useFrequency();
  const urlDot = "#";
  return (
    <div className="main__inner">
      {isPending && <div>Loading stats...</div>}
      {error && <div>{error}</div>}
      <ul className="main__task-list">
        {stats &&
          stats.map((stat) => (
            <li
              className={
                stat.title === "Self Care"
                  ? "main__task-item selfcare"
                  : `main__task-item ${stat.title.toLowerCase()}`
              }
              key={stat.id}
            >
              <div className="main__task-item-container">
                <h3 className="main__task-title">{stat.title}</h3>
                <a href={urlDot} className="main__task-dot">
                  <img src={Dot} alt="more details" />
                </a>
                <span className="main__task-current">
                  {/* {frequency === "daily"
                    ? stat.timeframes.daily.current
                    : frequency === "weekly"
                    ? stat.timeframes.weekly.current
                    : stat.timeframes.monthly.current}
                  hrs */}
                  {stat.timeframes[frequency].current}hrs
                </span>
                <span className="main__task-previous">
                  {frequency === "daily"
                    ? "Yesterday"
                    : frequency === "weekly"
                    ? "Last Week"
                    : "Last Month"}{" "}
                  -{" "}
                  {
                    /* {frequency === "daily"
                    ? stat.timeframes.daily.previous
                    : frequency === "weekly"
                    ? stat.timeframes.weekly.previous
                    : stat.timeframes.monthly.previous} */
                    stat.timeframes[frequency].previous
                  }
                  hrs
                </span>
              </div>
            </li>
          ))}
      </ul>
    </div>
  );
}

【问题讨论】:

    标签: reactjs json fetch


    【解决方案1】:

    从 GitHub 或其他存储库导入站点后,您可以在 Vercel 中配置环境变量。

    您可以通过单击环境变量选项卡在“配置项目”窗口中进行设置。 见下图

    【讨论】:

    • 谢谢。即使我阅读了vercel上的说明,我也不知道如何设置环境变量:(
    • 如果您还没有弄清楚,我希望这个视频对您有所帮助。 youtube.com/watch?v=lo2GmBahoyI
    • 我发现我需要使用第三方后端,因为即使我使用 env var,json-server 也无法部署在 vercel 上。不过非常感谢。
    • 我认为这是可能的。如果还没有阅读这篇文章,请阅读它。我会告诉你怎么做。 blog.devsharma.live/deploy-a-node-server-to-vercel
    猜你喜欢
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-08-21
    • 2020-08-27
    • 2020-12-05
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多