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

React Native 0.70.5电影搜索渲染错误修复:解决undefined is not an object问题

问题修复方案

核心错误原因

TMDB电影搜索接口的返回数据中,结果数组字段是results而非search,你错误地使用了data.search,导致results变量为undefined,后续调用map时触发“undefined is not an object”错误。

具体修改点

  • 修正接口数据提取:将let results = data.search改为let results = data.results || [],添加空值兜底避免数组为undefined。
  • 优化状态结构:将搜索关键词和结果拆分为独立的useState,逻辑更清晰。
  • 添加请求错误处理:为axios请求添加catch块,避免请求失败时程序崩溃。
  • 优化输入框提示:使用placeholder替代将提示文字作为输入框初始值,提升用户体验。
  • 添加加载状态:避免用户重复提交请求,同时给用户明确反馈。

修改后的完整代码

import React, { useState } from 'react';
import axios from 'axios';
import { View, StyleSheet, Text, TextInput, ScrollView, ActivityIndicator } from "react-native";

const Search = () => {
  const API_KEY = "XXX"; // 替换为你的TMDB API密钥
  const apiUrl = `https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}`;
  
  // 拆分状态,逻辑更清晰
  const [searchQuery, setSearchQuery] = useState("");
  const [movieResults, setMovieResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const searchMovies = async () => {
    if (!searchQuery.trim()) return; // 空查询不发起请求
    
    setIsLoading(true);
    try {
      const response = await axios.get(`${apiUrl}&query=${encodeURIComponent(searchQuery)}`);
      // 提取正确的结果字段,同时兜底空数组
      setMovieResults(response.data.results || []);
    } catch (error) {
      console.error("搜索失败:", error);
      setMovieResults([]); // 出错时清空结果
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        onChangeText={setSearchQuery}
        onSubmitEditing={searchMovies}
        value={searchQuery}
        placeholder="输入电影名称搜索"
        placeholderTextColor="#999"
      />
      
      {isLoading ? (
        <ActivityIndicator size="large" color="#000" style={styles.loader} />
      ) : (
        <ScrollView style={styles.resultsContainer}>
          {movieResults.length === 0 ? (
            <Text style={styles.emptyText}>暂无搜索结果</Text>
          ) : (
            movieResults.map(result => (
              <View key={result.id} style={styles.movieItem}>
                <Text style={styles.movieTitle}>{result.title}</Text>
              </View>
            ))
          )}
        </ScrollView>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    backgroundColor: "#fff",
  },
  input: {
    height: 40,
    borderColor: "#ccc",
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 12,
    marginBottom: 16,
  },
  loader: {
    flex: 1,
    justifyContent: "center",
  },
  resultsContainer: {
    flex: 1,
  },
  movieItem: {
    padding: 12,
    borderBottomWidth: 1,
    borderBottomColor: "#eee",
  },
  movieTitle: {
    fontSize: 16,
    fontWeight: "500",
  },
  emptyText: {
    textAlign: "center",
    marginTop: 40,
    color: "#666",
  },
});

export default Search;

额外说明

  • 使用encodeURIComponent处理搜索关键词,避免特殊字符导致请求错误。
  • 空结果提示和加载状态的加入,提升了整体用户体验。
  • 拆分状态后,代码的可读性和可维护性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 01:31:04