React新手求教:如何将Header组件中API请求的响应数据传递至其他组件?
Got it, let's figure out how to pass that API data from your Header component to another component. The most straightforward approach for this scenario is using callback props—it’s simple and works perfectly for parent-child component communication. Here’s how to implement it step by step:
Step 1: Update the Header Component to Accept a Callback Prop
We’ll modify your Header to receive a function prop (like onDataReceived) that triggers when the API call succeeds, passing the response data up to the parent component. Also, fix the URL definition to ensure it uses the latest ticker value every time you make a request:
import React, { useState } from 'react'; import Axios from 'axios'; const Header = ({ onDataReceived }) => { // Accept the callback prop const [ticker, setTicker] = useState(''); const getData = () => { // Move URL inside getData to use the latest ticker value const url = `https://cloud.iexapis.com/stable/stock/${ticker}/quote?token=${process.env.REACT_APP_API_KEY}`; Axios.get(url) .then((response) => { console.log(response.data); // Call the callback to pass data up to parent if (onDataReceived) { onDataReceived(response.data); } }) .catch(function(error) { console.log(error); // Optional: Add an error callback if you want to handle errors in parent // if (onError) onError(error); }); }; const handleKeypress = (e) => { if(e.keyCode === 13) { getData(); } }; return ( <div className='header'> <h1 id='brand'>Stock Tracker: {ticker}</h1> <div className='input-flow'> <input onChange={e => setTicker(e.target.value)} onKeyDown={handleKeypress} className='ticker-input' type='text' placeholder='Ticker Symbol' maxLength='5' minLength='1' /> <button className='add' onClick={getData} type='submit'>Add</button> </div> </div> ); }; export default Header;
Step 2: Manage Data in the Parent Component
Let’s assume your parent component is App.js. We’ll add state here to store the stock data, then pass a handler function to Header to update this state. Finally, we’ll pass the data to your target component (e.g., StockDetails):
import React, { useState } from 'react'; import Header from './Header'; import StockDetails from './StockDetails'; // Your component to display data function App() { const [stockData, setStockData] = useState(null); // State to hold API data // Handler to receive data from Header const handleStockDataReceived = (data) => { setStockData(data); }; return ( <div className="App"> {/* Pass the handler to Header */} <Header onDataReceived={handleStockDataReceived} /> {/* Render the target component only when data exists */} {stockData && <StockDetails data={stockData} />} </div> ); } export default App;
Step 3: Build the Target Component to Display Data
Here’s a quick example of StockDetails.js that accepts the data as a prop and renders it:
import React from 'react'; const StockDetails = ({ data }) => { return ( <div className='stock-details'> <h2>Stock Information</h2> <p>Company: {data.companyName}</p> <p>Latest Price: ${data.latestPrice}</p> <p>Change: {data.change} ({(data.changePercent * 100).toFixed(2)}%)</p> {/* Add more fields from the API response as needed */} </div> ); }; export default StockDetails;
Alternative Approaches for Larger Apps
If your app has deep component nesting or complex state needs, you could use:
- React Context API: To share data across multiple components without passing props manually at every level.
- State Management Libraries: Like Redux or Zustand, for handling global state across your entire application.
For your current use case though, callback props are the simplest and most efficient solution.
内容的提问来源于stack exchange,提问作者Ara

