【问题标题】:How to add a loader for slow network in React如何在 React 中为慢速网络添加加载器
【发布时间】:2026-02-13 05:20:03
【问题描述】:

我已经创建了一个订阅页面,并且在提交页面时不会像网络速度较慢的人那样重定向。有没有办法可以在提交按钮上放置一个加载器来解决这个问题,因为它会稍微破坏用户体验。这就是我的提交函数的样子。

const handleOnSubmit = (e) => {
    e.preventDefault();
    var body = {
      data: {
        name: name,
        email: email,
        contact_number: phone,
        organization: organization,
        designation: designation,
      },
    };

    // Send mailchimp data to lambda
    body = {
      data: {
        ...body.data,
        mailchimp: {
          email_address: email,
          status: newsletter ? "subscribed" : "unsubscribed",
          merge_fields: {
            FNAME: name,
            PHONE: phone,
            MMERGE6: organization,
            JOBTYPE: designation,
            SIGNUPSOUR: Book.fields.contentpieceId,
          },
        },
      },
    };
    setShowModal(false);
    if (window) {
      window.localStorage.setItem("@landing:sub-emai", email);
    }

    console.log(body);

    if (!isDanger) {
      axios
        .post(
          "{API}/prod/api",
          body
        )
        .then((resp) => {
          if (resp.status === 200) {
            window.location.href = `/case-study/${eBook.fields.redirectUrl}`;
          } else {
            setError(true);
          }
        });
    }
  };

【问题讨论】:

  • 维护一个状态变量来检测请求是否在进行中,然后根据该状态变量添加你需要的加载。
  • 如何检测请求是否正在进行?
  • 在顶部添加一个状态变量(requestIsInProgress: false),然后在axio调用之前更新它(requestIsInProgress: true),并在完成请求后再次更新它(在.then()回调中)@987654324 @,
  • 感谢您的解决方案,但我不明白这背后的内部工作,添加状态如何解决问题
  • 所以你有一个状态变量可以检测请求是否在进行中,然后根据状态变量你可以在html中显示一个加载器

标签: javascript reactjs http-post


【解决方案1】:

我根据您的数据提供了一个可能对您有所帮助的示例。我用默认值 false 创建了状态 loading。在获取数据时,您将 loading 设置为 true,完成后将 loading 设置为 false。如果 loading 设置为 true,它会向您显示微调器。

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

export default function MyComponent() {
    const [loading, setIsLoading] = useState(false);

    const handleOnSubmit = (e) => {
        e.preventDefault();
        setIsLoading(true) // data is fetching

        // do your job with axios

        axios.post("{API}/prod/api", "body")
            .then((resp) => {
                if (resp.status === 200) {
                    window.location.href = `/case-study/blw`;
                }
            })
            .catch((e) => console.log(e))
            .finally(function () {
                setIsLoading(false);
            })
    }

    return(
        <div>
            {loading && < Spinner/>}
            <div>
                <button type="submit" name="action">Submit</button>
            </div>
        </div>
    )
}

【讨论】: