简体   繁体   English

使用 axios 获取的数据在页面加载时闪烁

[英]Data fetched with axios flickering on page load

I'm building out a new marketing website for my company in Gatsby, utilizing axios to fetch data from a REST api to dynamically display a list of dealers, and then dynamically displaying the contact information of the chosen dealer throughout the site.我正在盖茨比为我的公司建立一个新的营销网站,利用axios从 REST api 获取数据以动态显示经销商列表,然后在整个网站上动态显示所选经销商的联系信息。 This is done by setting a cookie, which carries the ID of the dealer on the API, and then will fetch that dealer's info based on the cookie.这是通过设置一个cookie来完成的,cookie中带有API上经销商的ID,然后会根据cookie获取该经销商的信息。 However, I'm encountering an issue where the name of the dealer, which I'm currently displaying in the header, flickers on every page load.但是,我遇到了一个问题,即我目前在 header 中显示的经销商名称在每次加载页面时都会闪烁。 It looks bad, so I'm wondering if there is a way to either cache that data, or not force it to fetch on every page load and eliminate the flicker.它看起来很糟糕,所以我想知道是否有办法缓存该数据,或者不强制它在每次页面加载时获取并消除闪烁。 I'm still in development, so I've got it staged on Netlify here , and you can take a look at the live version.我还在开发中,所以我已经在 Netlify 上发布了它,你可以看看实时版本。

Here is my hook.这是我的钩子。

use-fetch.ts使用-fetch.ts

import { useEffect, useState } from 'react';
import axios from 'axios';

export const useFetch = (url: string) => {
  const [status, setStatus] = useState('idle');
  const [data, setData] = useState([]);

  useEffect(() => {
    if (!url) return;
    const fetchData = async () => {
      setStatus('fetching');
      const result = await axios(url);
      setData(result.data);
      setStatus('fetched');
    };

    fetchData();
  }, [url]);

  return { status, data };
};

I'm then able to consume this in the pages like so:然后我就可以像这样在页面中使用它:

const [query] = useState('https://jsonplaceholder.typicode.com/users/1/');
const url = query && 'https://jsonplaceholder.typicode.com/users/${cookie}';
const { data } = useFetch(url);

This sets an initial state users/1/ that will display the information for the first dealer unless a cookie is set.这设置了初始 state users/1/除非设置了 cookie,否则将显示第一个经销商的信息。

I use this in a layout component, and I can pass the data prop down to my Header component.我在布局组件中使用它,我可以将data属性传递给我的Header组件。

app-layout.tsx应用布局.tsx

import React, { ReactNode, useEffect, useState } from 'react';

import Logo from '../../assets/svg/logo.svg';

import { Header } from '../header/Header';
import { Footer } from '../footer/Footer';
import { Devtools } from '../devtools/Devtools';

import s from './AppLayout.scss';

import { useCookie } from 'hooks/use-cookie';
import { useFetch } from 'hooks/use-fetch';

interface AppLayoutProps {
  menuItems: any;
  children: ReactNode;
}

const isDev = process.env.NODE_ENV === 'development';

// tslint:disable no-default-export
export default ({ children, menuItems }: AppLayoutProps) => {
  // copyright year
  const [year, setDate] = useState<any>();

  // setting cookie to be referenced in the useFetch hook, setting the query for dealer specific information
  const [cookie] = useCookie('one-day-location', '1');

  // the API call
  const [query, setQuery] = useState('https://jsonplaceholder.typicode.com/users/1/');
  const url = query && `https://jsonplaceholder.typicode.com/users/${cookie}`;
  const { data } = useFetch(url);

  const getYear = () => setDate(new Date().getFullYear());

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

  return (
    <div className={s.layout}>
      <Header menuItems={menuItems} data={data}></Header>

      {children}

      <Footer menuItems={menuItems} logo={<Logo />} year={year} />

      {isDev && <Devtools />}
    </div>
  );
};

And this is my use-cookie hook that is referenced throughout these components:这是我在这些组件中引用的use-cookie挂钩:

use-cookie.ts使用 cookie.ts

import { useState } from 'react';
import Cookies from 'universal-cookie';

/**
 * Custom hook creates and returns cookie values.
 */
export const useCookie = (key: string, value: string) => {
  const cookies = new Cookies();
  const [cookie] = useState(() => {
    if (cookies.get(key)) {
      return cookies.get(key);
    }
    cookies.set(key, value);
  });

  const updateCookie = (value: string) => {
    removeItem(value);
    cookies.set(key, value);
  };

  const removeItem = (key: string) => {
    cookies.remove(key);
  };

  return [cookie, updateCookie, removeItem];
};

If you notice though, it flickers on every page load.但是,如果您注意到,它会在每次页面加载时闪烁。 Is there a way to store and display that data differently so that it won't do this?有没有办法以不同的方式存储和显示该数据,以便它不会这样做?

Thanks in advance.提前致谢。

So, I was able to figure out a better solution with a bit of digging.所以,我能够通过一些挖掘找到一个更好的解决方案。 Rather than trying to debug the hook that I built, I'm using axios-hooks , which has all of the same functionality that I needed, but solves the problem.我没有尝试调试我构建的挂钩,而是使用axios-hooks ,它具有我需要的所有相同功能,但可以解决问题。 In my layout, I've got the data being fetched like so:在我的布局中,我已经像这样获取数据:

const [cookie, updateCookie] = useCookie('one-day-location', '1');

const [{ data, loading, error }] = useAxios(
  `https://jsonplaceholder.typicode.com/users/${cookie}`,
);

And I'm then able to pass the data down to my Header component, but it doesn't load the API multiple times, and eliminates the flickering.然后我可以将数据向下传递到我的Header组件,但它不会多次加载 API,并消除了闪烁。 I can absolutely add more documentation here in my answer if anyone has any more questions.如果有人有任何问题,我绝对可以在我的回答中添加更多文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 页面闪烁,只取数据,没有复杂的逻辑。 什么会导致闪烁? 每次我打开页面都会发生 - Flickering of the pages, only data is being fetched, no complex logic. What can cause the flickering? Everytime i open the page it happens React Axios - 未列出获取的数据 - React Axios - The fetched data is not listed 使用 React useEffect() 获取的 Firestore 数据未在第一页加载时显示 - Fetched firestore data not displaying on first page load with React useEffect() 将用axios提取的json数据拆分为可点击的列表项,该列表项重定向到页面 - Split up json-data fetched with axios in to a clickable list-item that redirects to page reactjs - 在下次提取时使用提取的数据 (axios) - reactjs - use fetched data in next fetch (axios) 从React中的Axios返回获取的数据 - Return Fetched Data from Axios in React REST API 响应在页面加载时闪烁 - REST API Response Flickering on Page Load Material UI:页面初始加载时闪烁(Razzle) - Material UI:Flickering on the initial load of the page(Razzle) 反应-Axios数据一旦获取就不会呈现数据 - React - Axios data does not render the data once fetched 如何在 axios 在 componentDidMount 中获取数据后拍摄开玩笑的快照? - How to take a jest snapshot after axios fetched data in componentDidMount?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM