You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Axios获取接口数据后如何在React Native中实现图片网格

问题错误点说明

  • 状态取值错误:你声明的状态是const [pokemons, setPokemon] = useState([]),其中pokemons才是存储宝可梦数据的状态变量,setPokemon是用来更新状态的方法,你从setPokemon里解构data属于错误操作,这里根本拿不到数据。
  • renderItem参数格式错误:FlatList的renderItem属性传入的函数接收的是一个包含item、index等属性的对象,你直接写(item, index)拿到的不是单条宝可梦数据,自然渲染不出来。
  • 缺少网格配置:要实现图片网格效果,需要给FlatList添加numColumns属性指定每行展示的数量,同时要拼接宝可梦的官方图片地址才能渲染图片。
  • 异步请求缺少catch分支:请求报错时没有捕获逻辑,不利于问题排查。

修改后可运行的完整代码

import { useState, useEffect } from 'react';
import { SafeAreaView, FlatList, Text, StyleSheet, Image, View } from 'react-native';
import axios from 'axios';

export default function App() {
  const [pokemons, setPokemon] = useState([])

  // 拉取宝可梦数据
  async function fetchPokemon() {
    try {
      const { data } = await axios.get('https://pokeapi.co/api/v2/pokemon?limit=50')
      setPokemon(data.results)
    } catch (err) {
      console.log('请求失败:', err)
    }
  }

  useEffect(() => {
    fetchPokemon()
  }, [])

  // 渲染单条宝可梦卡片
  const renderPokemon = ({item}) => {
    // 从宝可梦接口url中提取id,拼接官方图片地址
    const id = item.url.split('/').slice(-2, -1)[0]
    const imageUrl = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${id}.png`
    return (
      <View style={styles.card}>
        <Image source={{uri: imageUrl}} style={styles.pokemonImage} />
        <Text>{item.name}</Text>
      </View>
    )
  }

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={pokemons} // 直接传入存储数据的状态变量pokemons
        renderItem={renderPokemon}
        keyExtractor={pokemon => `key-${pokemon.name}`}
        numColumns={3} // 每行展示3个,可根据需求调整数值修改网格列数
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingHorizontal: 8,
  },
  card: {
    flex: 1,
    alignItems: 'center',
    margin: 8,
    padding: 12,
    borderRadius: 8,
    backgroundColor: '#f5f5f5'
  },
  pokemonImage: {
    width: 80,
    height: 80,
    marginBottom: 8
  }
});

修改后启动项目即可看到3列布局的宝可梦图片网格,调整numColumns的数值就能改成你需要的网格列数。

内容的提问来源于stack exchange,提问作者mmiah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:06:07