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

React Native调用REST API时JSON对象转字符串显示[object Object]问题

Fix: React Native Showing [object Object] Instead of Movie Data

Hey, let's break down what's going wrong here and fix it step by step:

The Root Cause

Your getMovies() function returns a Promise object, not the actual movie data array. Since getMoviesFromApiAsync() uses fetch (which is asynchronous), it returns a Promise that resolves to your data later—right now, you're trying to convert that Promise to a string, which gives you [object Object].

React components need to handle asynchronous data properly using state, so let's adjust your code to manage this correctly.

Fixed Code

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {
  // Initialize state to track movies, loading status, and errors
  state = {
    movies: [],
    isLoading: true,
    error: null,
  };

  // Fetch data when the component finishes mounting
  componentDidMount() {
    this.getMoviesFromApiAsync();
  }

  // Rewrite async function with async/await for readability
  async getMoviesFromApiAsync() {
    try {
      const response = await fetch('https://facebook.github.io/react-native/movies.json');
      const responseJson = await response.json();
      // Update state with movie data once fetch completes
      this.setState({
        movies: responseJson.movies,
        isLoading: false,
      });
    } catch (error) {
      this.setState({
        error: error.message,
        isLoading: false,
      });
      console.error(error);
    }
  }

  render() {
    const { isLoading, movies, error } = this.state;

    // Show loading state while data is being fetched
    if (isLoading) {
      return (
        <View style={styles.container}>
          <Text>Loading movies...</Text>
        </View>
      );
    }

    // Show error message if fetch fails
    if (error) {
      return (
        <View style={styles.container}>
          <Text>Error loading data: {error}</Text>
        </View>
      );
    }

    // Render the full UI with movie data once ready
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>
        {/* Map through movie array to display each entry properly */}
        <View style={styles.movieList}>
          {movies.map((movie, index) => (
            <Text key={index} style={styles.movieItem}>
              * {movie.title} ({movie.releaseYear})
            </Text>
          ))}
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  movieList: {
    marginTop: 20,
    alignItems: 'flex-start',
    paddingHorizontal: 20,
  },
  movieItem: {
    fontSize: 16,
    marginBottom: 8,
  },
});

Key Changes Explained

  • State Management: We added component state to track movie data, loading status, and errors. This triggers React to re-render the component automatically when data is ready.
  • Async/Await: Switched to async/await for cleaner, more readable asynchronous code (you could still use .then() chains if you prefer).
  • Conditional Rendering: We handle three states: loading, error, and successful data load—giving users clear feedback at each step.
  • Proper Data Display: Instead of trying to convert an object to a string, we use map to loop through the movie array and display each movie's title and release year in a readable format.

内容的提问来源于stack exchange,提问作者joe the coder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:09:27