如何优化从JSON中提取数据

huangapple go评论68阅读模式
英文:

how to optimize fetching data from JSON

问题

有没有办法更快地获取数据并确定数据长度,而不需要加载所有JSON数据。

以下是代码

const url = "https://jsonplaceholder.typicode.com/comments";
const [data, setData] = useState([]);
const [colorScheme, setColorScheme] = useState(true);
const [loader, setLoader] = useState(true);

const rand = (param) => Math.ceil(Math.random() * param);

async function fetchData() {
  try {
    // const templ = await axios.get(url);
    const res = await axios.get(
      url + `?id=${rand((await axios.get(url)).data.length)}`
    );
    setData(res.data);
    setLoader(false);
    console.warn(data);
  } catch (error) {
    console.error(error);
  }
}

useEffect(() => {
  fetchData();
}, []);

尝试过缓存数据,但我想要一个更高效的选项。

英文:

Is there any solutions of fetching data more fast and determine data length without loading all JSON data.

Here is code

const url = "https://jsonplaceholder.typicode.com/comments";
  const [data, setData] = useState([]);
  const [colorScheme, setColorScheme] = useState(true);
  const [loader, setLoader] = useState(true);

  const rand = (param) => Math.ceil(Math.random() * param);

  async function fetchData() {
    try {
      // const templ = await axios.get(url);
      const res = await axios.get(
        url + `?id=${rand((await axios.get(url)).data.length)}`
      );
      setData(res.data);
      setLoader(false);
      console.warn(data);
    } catch (error) {
      console.error(error);
    }
  }

  useEffect(() => {
    fetchData();
  }, []);

Tried to cache data, but I want a more efficient option

答案1

得分: 0

目前,代码进行了两次API调用,一次用于获取数据的长度,然后再获取一个随机评论。最好是进行单个API调用以获取数据,然后从中随机选择一条评论。像这样:

const [data, setData] = useState([]);
const [colorScheme, setColorScheme] = useState(true);
const [loading, setLoading] = useState(true);

const fetchData = useCallback(async () => {
  try {
    const response = await axios.get(url);
    const comments = response.data;
    const randomComment = comments[Math.floor(Math.random() * comments.length)];
    setData(randomComment);
    setLoading(false);
  } catch (error) {
    console.error(error);
    setLoading(false);
  }
}, []);

useEffect(() => {
  fetchData();
}, [fetchData]);
英文:

Currently, the code makes two API calls to get the length of the data and then fetch a random comment. It's better to make a single API call to fetch the data and then randomly select a comment from it. Like this:

<!-- language: lang-js -->

const [data, setData] = useState([]);
  const [colorScheme, setColorScheme] = useState(true);
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () =&gt; {
    try {
      const response = await axios.get(url);
      const comments = response.data;
      const randomComment = comments[rand(comments.length) - 1];
      setData(randomComment);
      setLoading(false);
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  }, []);

  useEffect(() =&gt; {
    fetchData();
  }, [fetchData]);

<!-- end snippet -->

答案2

得分: 0

为了更高效地获取数据并在不加载所有 JSON 数据的情况下确定数据长度,您可以使用API提供的分页和筛选机制。JSONPlaceholder API,您在示例中使用的API,支持各种查询参数,允许您获取特定数量的项目或根据特定条件筛选数据。

以下是如何实现分页和筛选以更高效地获取数据的示例:

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

const url = "https://jsonplaceholder.typicode.com/comments";
const itemsPerPage = 10; // 设置每页要获取的项目数量

const fetchData = async (page) => {
  try {
    const res = await axios.get(url, {
      params: {
        _page: page,
        _limit: itemsPerPage,
      },
    });
    return res.data;
  } catch (error) {
    console.error(error);
    return [];
  }
};

const Home = () => {
  const [data, setData] = useState([]);
  const [colorScheme, setColorScheme] = useState(true);
  const [loader, setLoader] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    const fetchInitialData = async () => {
      const initialData = await fetchData(currentPage);
      setData(initialData);
      setLoader(false);
    };
    fetchInitialData();
  }, [currentPage]);

  const handleLoadMore = async () => {
    const nextPage = currentPage + 1;
    const moreData = await fetchData(nextPage);
    setData((prevData) => [...prevData, ...moreData]);
    setCurrentPage(nextPage);
  };

  // 这里是您的渲染逻辑
};

export default Home;

使用这种方法,您首先从API中获取有限数量的项目(例如,10个项目)。当您想要加载更多数据时,调用handleLoadMore函数,该函数获取下一页的数据(下一个10个项目)并将它们附加到现有数据中。这样,您可以逐步加载数据,而不会一次性加载所有 JSON 数据。

此外,您可以使用查询参数如_start_end_sort_order来实现更高级的筛选选项。这些参数允许您获取特定范围的数据、对数据进行排序,或根据API的能力应用自定义筛选。

请记得调整itemsPerPage变量以控制每页要获取的项目数量。这将帮助您平衡每个请求中获取的数据量。

英文:

To fetch data more efficiently and determine data length without loading all JSON data, you can use pagination and filtering mechanisms provided by the API. The JSONPlaceholder API, which you are using in your example, supports various query parameters that allow you to fetch a specific number of items or filter the data based on certain criteria.

Here's an example of how you can implement pagination and filtering to fetch data more efficiently:

import React, { useState, useEffect } from &quot;react&quot;;
import axios from &quot;axios&quot;;

const url = &quot;https://jsonplaceholder.typicode.com/comments&quot;;
const itemsPerPage = 10; // Set the number of items you want to fetch per page

const fetchData = async (page) =&gt; {
  try {
    const res = await axios.get(url, {
      params: {
        _page: page,
        _limit: itemsPerPage,
      },
    });
    return res.data;
  } catch (error) {
    console.error(error);
    return [];
  }
};

const Home = () =&gt; {
  const [data, setData] = useState([]);
  const [colorScheme, setColorScheme] = useState(true);
  const [loader, setLoader] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() =&gt; {
    const fetchInitialData = async () =&gt; {
      const initialData = await fetchData(currentPage);
      setData(initialData);
      setLoader(false);
    };
    fetchInitialData();
  }, [currentPage]);

  const handleLoadMore = async () =&gt; {
    const nextPage = currentPage + 1;
    const moreData = await fetchData(nextPage);
    setData((prevData) =&gt; [...prevData, ...moreData]);
    setCurrentPage(nextPage);
  };

  // Your rendering logic here
};

export default Home;

With this approach, you initially fetch a limited number of items (e.g., 10 items) from the API. When you want to load more data, you call the handleLoadMore function, which fetches the next page of data (the next 10 items) and appends them to the existing data. This way, you can load data incrementally, and you won't load all the JSON data at once.

Additionally, you can implement more advanced filtering options by using query parameters like _start, _end, _sort, and _order. These parameters allow you to fetch specific ranges of data, sort the data, or apply custom filtering based on the API's capabilities.

Remember to adjust the itemsPerPage variable to control how many items you want to fetch per page. This will help you balance the amount of data fetched in each request.

huangapple
  • 本文由 发表于 2023年7月28日 00:16:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76781664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定