React异步请求数据后无法通过Props传递给子组件的解决方案
问题
需要实现以下场景:先发起请求并验证服务器响应,再展示UI,同时将完整响应传递给子组件。现有代码能获取正确的服务器响应,但无法通过props传递给CarsGrid组件——控制台能打印响应结果,却无法打印子组件接收的gridRows参数。
相关代码如下:
index.tsx
ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') );
App.tsx
import React from "react"; import logo from "./logo.svg"; import "./App.css"; import { CarsGrid } from "./CarsGrid"; const init = async () => { try { const response = await fetch( "https://www.ag-grid.com/example-assets/row-data.json" ) return await response.json(); } catch (err) {} }; function App() { init().then(result=> { console.log('Correct Response is printed',result); return <CarsGrid gridRows={result} />; }); return (<></>) } export default App;
CarsGrid组件
export function CarsGrid({gridRows}) { console.log('Data gridRows', gridRows); })
解决方法
你的核心问题是:在App组件函数里调用init()后,then回调返回的CarsGrid组件根本没被React的渲染流程识别——组件函数的返回值才是要渲染的内容,而你最终一直返回空的<> </>,导致CarsGrid从未被挂载,自然不会打印参数。
正确做法是用React状态管理异步请求结果,步骤如下:
修改后的App.tsx
import React, { useState, useEffect } from "react"; import "./App.css"; import { CarsGrid } from "./CarsGrid"; // 封装请求逻辑 const fetchCarData = async () => { try { const response = await fetch( "https://www.ag-grid.com/example-assets/row-data.json" ); // 验证响应状态 if (!response.ok) throw new Error(`请求失败,状态码:${response.status}`); return await response.json(); } catch (err) { console.error('获取数据出错:', err); return []; // 出错时返回空数组,避免子组件报错 } }; function App() { // 用状态存储请求结果和加载状态 const [gridRows, setGridRows] = useState([]); const [isLoading, setIsLoading] = useState(true); // 组件挂载时发起请求 useEffect(() => { const loadData = async () => { const data = await fetchCarData(); setGridRows(data); setIsLoading(false); }; loadData(); }, []); // 加载状态下显示提示 if (isLoading) { return <div>加载中...</div>; } // 数据加载完成后渲染子组件并传递props return <CarsGrid gridRows={gridRows} />; } export default App;
修正后的CarsGrid组件
export function CarsGrid({ gridRows }) { console.log('Data gridRows', gridRows); // 这里可以添加实际的表格渲染逻辑 return <div>共{gridRows.length}条车辆数据</div>; }
关键说明
useEffect的空依赖数组[]确保请求仅在组件挂载时执行一次- 新增
isLoading状态,给用户提供加载反馈,避免页面空白 - 增加响应状态验证
!response.ok,仅处理成功的服务器响应 - 错误处理中返回空数组,防止子组件因接收
undefined抛出异常
内容的提问来源于stack exchange,提问作者Raj
相关产品推荐
相关产品推荐

