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

React调用API拉取数据后导出变量fearvalue未成功保存值问题求助

问题原因
  • 执行时机不匹配:你把请求绑定在window.load事件上,这个事件需要等待页面所有资源(图片、样式等)全部加载完成才触发,而React App组件的初始化、首次渲染远早于这个时机,所以组件第一次读取fearvalue时还是初始的空数组。
  • 外部变量修改无法触发组件更新:ES模块的导入是静态绑定,即使后续你修改了导出的fearvalue变量,React组件不会感知到外部普通变量的变化,自然不会触发重新渲染,页面也就不会更新。
  • 同步XHR已经被废弃:你设置了open的第三个参数为false开启同步请求,会阻塞主线程,导致页面卡顿,现在主流浏览器都不推荐这种用法。
解决方案

调整逻辑把请求结果存入React的状态中,靠状态更新驱动组件重渲染即可:

修改Bitcoin Fear&Greed.js代码

// 移除全局导出的fearvalue和window.load绑定逻辑
export const fearAndGreed = async () => {
  return new Promise((resolve, reject) => {
    let bitcoinAPY = new XMLHttpRequest();
    bitcoinAPY.open("GET", "https://api.alternative.me/fng/?limit=10&date_format=us");
    bitcoinAPY.onload = () => {
      if (bitcoinAPY.status >= 200 && bitcoinAPY.status < 300) {
        const data = JSON.parse(bitcoinAPY.response);
        resolve(data.data[0]);
      } else {
        reject(new Error('请求失败'));
      }
    };
    bitcoinAPY.onerror = () => reject(new Error('网络错误'));
    bitcoinAPY.send();
  })
}

修改App组件代码

import './App.css';
import './Apy_TAPI';
import { DataFormatting } from './DataFormatting.js';
import { fearAndGreed } from './Bitcoin Fear&Greed';
import { useState, useEffect } from 'react';

function App() {
  // 用state存储请求结果,变更时自动触发组件重渲染
  const [fearvalue, setFearvalue] = useState(null);
  const test1 = "test1"

  // 组件挂载后发起请求
  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fearAndGreed();
        setFearvalue(res);
        console.log(res);
      } catch (err) {
        console.error('请求恐惧贪婪指数失败:', err);
      }
    }
    fetchData();
  }, [])

  console.log(fearvalue)

  return (
    <div className="App">
      <header className="App-header">
        <p>
          Bitcoin analyst tool
        </p>
      </header>
      <div className='Text'>
        <h1>
          <img className="Image" src="https://alternative.me/crypto/fear-and-greed-index.png" alt="Latest Crypto Fear & Greed Index" />
        </h1>
        <h2>
          https://bitinfocharts.com/pl/bitcoin/address/1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ <br />
          <br />
          {/* 对象不能直接渲染,按需取属性或者转成字符串展示 */}
          {fearvalue ? JSON.stringify(fearvalue) : '加载中...'} <br />
        </h2>
      </div>
    </div>
  );
}
export default App;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:06:05