You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React加载状态isLoading不显示Loading文本 组件意外重复渲染问题

问题解答

问题1:Loading文本始终不展示

  • 根本原因:fetch 是异步执行的,你把 setIsLoading(false) 直接写在 fetch 调用的同级同步代码位置,实际执行顺序为:setIsLoading(true) → 发起异步fetch请求 → 立即执行setIsLoading(false),不等fetch返回结果就把加载状态重置为false,自然看不到加载提示。
  • 修复方法:把 setIsLoading(false) 移动到fetch的异步回调末尾,同时补充错误捕获逻辑,避免请求失败时加载状态一直为true:
function fetchNFTHandler(owner) {
  setIsLoading(true);
  fetch(
    `https://api.opensea.io/api/v1/assets?owner=${owner}&order_direction=desc&offset=0&limit=10`
  )
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      const tranformedData = data.assets.map((element, index) => {
        return {
          title: element.name,
          id: index,
        };
      });
      setData(tranformedData);
      // 异步请求成功后再关闭加载状态
      setIsLoading(false);
    })
    .catch(err => {
      console.error('请求失败:', err);
      // 请求失败也要关闭加载状态
      setIsLoading(false);
    });
  // 删除原来写在这里的同步执行的setIsLoading(false)
}

问题2:未点击提交按钮,输入字符时就会打印isLoading日志

  • 根本原因:你给输入框绑定了onChange事件,每输入一个字符都会触发setEnteredWallet修改状态,React组件的状态发生变更就会触发整个组件重新渲染,组件函数体内部的所有代码(包括你写在return里的console.log("isLoading:", isLoading))都会在每次渲染时重新执行,所以会反复打印日志。
  • 优化方法:如果只需要在isLoading变化时打印日志,可以使用useEffect监听指定状态:
import { useState, useEffect } from "react";
// ...组件内部代码
useEffect(() => {
  console.log("isLoading:", isLoading);
}, [isLoading]) // 仅当isLoading变化时才执行回调

内容的提问来源于stack exchange,提问作者somniumm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 05:09:01