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
相关产品推荐
相关产品推荐

