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

React Native中合并两个API数据后用FlatList展示的问题求助

解决React Native中FlatList展示合并API数据的问题

步骤1:调整状态变量

不需要单独维护两个数据状态,直接用一个状态存储合并后的结果:

const [mergedData, setMergedData] = useState([]);

步骤2:修正API变量名并合并数据

你的代码里存在变量名不一致的问题(APIone vs API_one),先修正这个,再根据两个API的关联关系(posts的id对应comments的postId)合并数据:

const fetchData = () => {
  const APIone = 'https://jsonplaceholder.typicode.com/posts';
  const APItwo = 'https://jsonplaceholder.typicode.com/comments';
  const get_api_one = axios.get(APIone);
  const get_api_two = axios.get(APItwo);
  
  axios.all([get_api_one, get_api_two]).then(
    axios.spread((postsRes, commentsRes) => {
      // 注意:axios响应的实际数据存在data属性中
      const posts = postsRes.data;
      const comments = commentsRes.data;
      
      // 合并逻辑:给每篇文章绑定对应的评论
      const merged = posts.map(post => ({
        ...post,
        comments: comments.filter(comment => comment.postId === post.id)
      }));
      
      // 更新状态
      setMergedData(merged);
    })
  ).catch(err => {
    console.error('请求失败:', err);
  });
};

步骤3:渲染FlatList

在组件中添加FlatList,配置核心属性完成渲染:

return (
  <View style={{ flex: 1, padding: 16 }}>
    <FlatList
      data={mergedData}
      keyExtractor={(item) => item.id.toString()}
      renderItem={({ item }) => (
        <View style={{ marginBottom: 20, padding: 12, backgroundColor: '#f5f5f5', borderRadius: 8 }}>
          <Text style={{ fontSize: 18, fontWeight: 'bold', marginBottom: 8 }}>{item.title}</Text>
          <Text style={{ marginBottom: 12 }}>{item.body}</Text>
          <Text style={{ fontSize: 16, fontWeight: '600', marginBottom: 6 }}>评论:</Text>
          {item.comments.map(comment => (
            <Text key={comment.id} style={{ marginBottom: 4, color: '#666' }}>
              • {comment.name}: {comment.body}
            </Text>
          ))}
        </View>
      )}
    />
  </View>
);

完整代码整合

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

const App = () => {
  const [mergedData, setMergedData] = useState([]);

  const fetchData = () => {
    const APIone = 'https://jsonplaceholder.typicode.com/posts';
    const APItwo = 'https://jsonplaceholder.typicode.com/comments';
    const get_api_one = axios.get(APIone);
    const get_api_two = axios.get(APItwo);
    
    axios.all([get_api_one, get_api_two]).then(
      axios.spread((postsRes, commentsRes) => {
        const posts = postsRes.data;
        const comments = commentsRes.data;
        
        const merged = posts.map(post => ({
          ...post,
          comments: comments.filter(comment => comment.postId === post.id)
        }));
        
        setMergedData(merged);
      })
    ).catch(err => {
      console.error('请求失败:', err);
    });
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <View style={styles.container}>
      <FlatList
        data={mergedData}
        keyExtractor={(item) => item.id.toString()}
        renderItem={({ item }) => (
          <View style={styles.postCard}>
            <Text style={styles.postTitle}>{item.title}</Text>
            <Text style={styles.postBody}>{item.body}</Text>
            <Text style={styles.commentsTitle}>评论:</Text>
            {item.comments.map(comment => (
              <Text key={comment.id} style={styles.commentText}>
                • {comment.name}: {comment.body}
              </Text>
            ))}
          </View>
        )}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: '#fff'
  },
  postCard: {
    marginBottom: 20,
    padding: 12,
    backgroundColor: '#f5f5f5',
    borderRadius: 8
  },
  postTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 8
  },
  postBody: {
    marginBottom: 12,
    color: '#333'
  },
  commentsTitle: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 6
  },
  commentText: {
    marginBottom: 4,
    color: '#666'
  }
});

export default App;

关键提示

  • 如果不需要关联文章和评论,直接用[...posts, ...comments]就能完成简单合并
  • FlatList必须设置keyExtractor,否则会触发渲染警告
  • 加上错误捕获能快速排查API请求问题

内容的提问来源于stack exchange,提问作者Muhammad Kashif Nabeel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:50:34