React JS中实现三个按钮分别调用不同API并在控制台输出对应数据的技术需求问询
嘿,我来帮你搞定这个需求!下面是一个完整的React组件示例,正好实现你要的三个按钮分别调用独立API、并把返回数据输出到控制台的功能:
完整React组件代码
import { useState } from 'react'; function ApiCallButtons() { // 三个独立的API请求函数 const fetchData1 = async () => { try { const response = await fetch('https://api.example.com/data1'); if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); console.log('API 1 返回数据:', data); } catch (error) { console.error('API 1 请求出错:', error); } }; const fetchData2 = async () => { try { const response = await fetch('https://api.example.com/data2'); if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); console.log('API 2 返回数据:', data); } catch (error) { console.error('API 2 请求出错:', error); } }; const fetchData3 = async () => { try { const response = await fetch('https://api.example.com/data3'); if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); console.log('API 3 返回数据:', data); } catch (error) { console.error('API 3 请求出错:', error); } }; return ( <div style={{ padding: '20px', gap: '10px', display: 'flex' }}> <button onClick={fetchData1} style={{ padding: '8px 16px' }}> 调用API 1 </button> <button onClick={fetchData2} style={{ padding: '8px 16px' }}> 调用API 2 </button> <button onClick={fetchData3} style={{ padding: '8px 16px' }}> 调用API 3 </button> </div> ); } export default ApiCallButtons;
关键细节说明
- 独立逻辑拆分:每个按钮对应一个单独的异步函数,这样你后续要修改某个API的请求逻辑时,直接改对应的函数就行,不会影响其他按钮的功能。
- 错误处理:每个请求都加了
try/catch,就算API请求失败(比如网络问题、接口报错),也不会导致组件崩溃,还能把错误信息打印出来方便你调试。 - 响应校验:加了
!response.ok的判断,确保只有当HTTP状态码是2xx的时候才继续解析数据,避免拿到错误的响应内容。
可选扩展建议
- 要是你的API需要传参数,比如用户ID,可以给函数加参数,比如
fetchData1(userId),然后在按钮的onClick里写成() => fetchData1(123)就行。 - 可以给按钮加个加载状态,比如点击后禁用按钮或者显示“加载中”的文本,这样用户能知道请求正在处理,体验更好。
内容的提问来源于stack exchange,提问作者Jagadeesh
相关产品推荐
相关产品推荐

