React使用Fetch API报错:TypeError: ticker.map is not a function
Hey, let's figure out why you're hitting that error!
First off, the root cause is simple: the ticker data coming from the API isn't an array—it's a plain JavaScript object. The map() method only works on arrays, so when you try to call it on an object, JavaScript throws that "not a function" error.
If you check the response from the API you're using, the ticker field looks something like this (key-value pairs wrapped in an object):
{ "high": "100000000", "low": "95000000", "vol_btc": "123.45", "vol_idr": "12345678901", "last": "97500000", "buy": "97400000", "sell": "97500000", "server_time": 1620000000 }
Here are two straightforward fixes depending on what you want to display:
Fix 1: Show specific fields directly
If you only need to display certain values (like high and low), you don't need map at all—just access the object properties directly:
class App extends Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, ticker: {} // Initialize as empty object instead of array for clarity }; } componentDidMount() { fetch("https://vip.bitcoin.co.id/api/btc_idr/ticker") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, ticker: result.ticker }); }, (error) => { this.setState({ isLoaded: true, error }); } ) } render() { const { error, isLoaded, ticker } = this.state; if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <div className="ticker-container"> <h3>BTC-IDR Ticker</h3> <p>High Price: {ticker.high} IDR</p> <p>Low Price: {ticker.low} IDR</p> <p>Last Trade: {ticker.last} IDR</p> </div> ); } } }
Fix 2: List all ticker fields (convert object to array)
If you want to display every key-value pair in the ticker object, convert it to an array using Object.entries() (this gives you an array of [key, value] pairs), then use map on that array:
class App extends Component { constructor(props) { super(props); this.state = { error: null, isLoaded: false, ticker: {} }; } componentDidMount() { fetch("https://vip.bitcoin.co.id/api/btc_idr/ticker") .then(res => res.json()) .then( (result) => { this.setState({ isLoaded: true, ticker: result.ticker }); }, (error) => { this.setState({ isLoaded: true, error }); } ) } render() { const { error, isLoaded, ticker } = this.state; if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <ul className="ticker-list"> {Object.entries(ticker).map(([key, value]) => ( <li key={key}> <strong>{key.replace('_', ' ')}:</strong> {value} </li> ))} </ul> ); } } }
The main takeaway here is always double-check the structure of the API response you're working with—mixing up objects and arrays is a super common gotcha when fetching data in React!
内容的提问来源于stack exchange,提问作者Ras

