如何在ReactJS中保存API响应为变量并在任意组件中调用?
解决方案
问题1:修改组件以获取USD值
你的API返回的是单个对象{"USD":1168.64},不是数组,所以原来的persons数组状态和map遍历逻辑完全不适用。重新调整组件逻辑,直接提取并保存USD值:
import React from 'react'; import axios from 'axios'; export default class PersonList extends React.Component { state = { usdValue: null, isLoading: true, error: null } componentDidMount() { axios.get(`https://myendpoint.com`) .then(res => { // 直接从响应数据中提取USD字段 const usdValue = res.data.USD; this.setState({ usdValue, isLoading: false }); // 可选:如果要把数据传给父组件,调用传入的回调函数 this.props.onDataFetched?.(usdValue); }) .catch(err => { this.setState({ error: err.message, isLoading: false }); }) } render() { const { usdValue, isLoading, error } = this.state; if (isLoading) return <div>加载中...</div>; if (error) return <div>数据加载失败:{error}</div>; return <div>USD汇率:{usdValue}</div>; } }
问题2:在其他组件中使用API响应值
你导入的PersonList是React组件类,不是数据变量,所以直接console.log(PersonList)只会输出组件类本身。要获取API返回的值,有两种常用方式:
方式1:通过父组件中转数据
在父组件中通过回调函数接收PersonList传来的数据,再把数据传给其他组件:
// 父组件(比如App.js) import React, { useState } from 'react'; import PersonList from './components/PersonList'; import AnotherComponent from './components/AnotherComponent'; function App() { const [usdRate, setUsdRate] = useState(null); // 定义回调函数,接收PersonList传来的USD值 const handleDataReceived = (value) => { setUsdRate(value); console.log('获取到的USD值:', value); }; return ( <div> <PersonList onDataFetched={handleDataReceived} /> {/* 把USD值传给其他组件 */} <AnotherComponent usdRate={usdRate} /> </div> ); } export default App;
其他组件接收数据的示例:
// AnotherComponent.js import React from 'react'; export default function AnotherComponent({ usdRate }) { if (!usdRate) return <div>等待数据加载...</div>; return <div>其他组件展示USD汇率:{usdRate}</div>; }
方式2:抽离独立的数据获取函数
把API请求逻辑单独封装成工具函数,让任何组件都可以直接调用获取数据:
// api.js import axios from 'axios'; export const fetchUsdRate = async () => { try { const response = await axios.get('https://myendpoint.com'); return response.data.USD; } catch (error) { console.error('获取USD汇率失败:', error); throw error; } };
然后在需要的组件中使用:
// 任意组件 import React, { useState, useEffect } from 'react'; import { fetchUsdRate } from './api'; export default function AnyComponent() { const [usdRate, setUsdRate] = useState(null); useEffect(() => { async function getRate() { const rate = await fetchUsdRate(); setUsdRate(rate); console.log('USD汇率:', rate); } getRate(); }, []); return <div>{usdRate ? `当前USD汇率:${usdRate}` : '加载中...'}</div>; }
内容的提问来源于stack exchange,提问作者admin admin
相关产品推荐
相关产品推荐

