如何在React Native中用Axios获取数据并渲染到FlatList?
Fixing Axios Data Rendering in React Native FlatList
Hey, let's break down what's going wrong here and fix it step by step! Your code has a few key issues that are preventing the API data from showing up in the FlatList:
- You’re calling Axios directly in the component’s top-level scope, which means it runs every time the component re-renders (wasting resources) and you can’t access the async response outside the
thencallback. - The line
const res = res;is completely invalid—this variable doesn’t reference the API response at all, so your FlatList is trying to renderundefineddata. - There’s no state management to trigger a re-render once the API data is actually available.
Step-by-Step Solution
1. Use React State to Store Data
We’ll use the useState hook to hold the API response. This lets React know when to re-render the component once the data loads.
2. Wrap Axios in useEffect
Put the API call inside useEffect with an empty dependency array to ensure it only runs once when the component mounts.
3. Handle Async Response Correctly
Update your state inside the Axios then callback once the data is ready. We’ll also add loading and error states to improve user experience.
Corrected Full Code
import Axios from "axios"; import React, { useState, useEffect } from "react"; import { StyleSheet, Text, View, ActivityIndicator, Alert } from "react-native"; import { FlatList } from "react-native-gesture-handler"; export default function App() { // Initialize state for data, loading status, and errors const [products, setProducts] = useState([]); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { Axios({ method: "GET", url: "https://bitbucket.org/!api/2.0/snippets/kamalo11/9nab7z/2ab26f49667b945a4e78679492fc7950bc1df3be/files/ecommerce.json", }) .then((res) => { // Save the fetched data to state setProducts(res.data); setIsLoading(false); // Mark loading as complete }) .catch((err) => { console.error(err); setError(err.message); setIsLoading(false); Alert.alert("Oops!", "Failed to load product data"); }); }, []); // Empty dependency array = run once on component mount // Show loading spinner while data is fetching if (isLoading) { return ( <View style={styles.container}> <ActivityIndicator size="large" color="#0066cc" /> </View> ); } // Show error message if something goes wrong if (error) { return ( <View style={styles.container}> <Text style={styles.errorText}>Error: {error}</Text> </View> ); } // Render FlatList once data is ready return ( <View style={styles.container}> <FlatList data={products} keyExtractor={(item) => item.id.toString()} renderItem={({ item }) => ( <View style={styles.productItem}> <Text style={styles.productName}>{item.name}</Text> <Text style={styles.productPrice}>${item.price}</Text> </View> )} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 20, paddingHorizontal: 15, backgroundColor: "#f5f5f5", }, productItem: { backgroundColor: "white", padding: 18, borderRadius: 8, marginBottom: 12, shadowColor: "#000", shadowOffset: { width: 0, height: 2 }, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3, }, productName: { fontSize: 16, fontWeight: "500", marginBottom: 6, }, productPrice: { fontSize: 14, color: "#0066cc", fontWeight: "600", }, errorText: { fontSize: 16, color: "#cc0000", textAlign: "center", marginTop: 20, }, });
Key Changes Explained
- State Management:
useStatekeeps track of the product list, loading state, and errors. When we update these states withsetProducts, React automatically re-renders the FlatList with the new data. useEffect: Ensures the API call only runs once when the component first loads, preventing redundant requests.- Async Handling: We wait for the Axios promise to resolve before updating state—this guarantees we only pass valid data to the FlatList.
- User Feedback: Loading spinners and error alerts make the app feel more responsive and help users understand what’s happening.
内容的提问来源于stack exchange,提问作者user13911708
相关产品推荐
相关产品推荐

