簡體   English   中英

在不顯示[object Object]的情況下,React Native REST API不會將JSON對象轉換為String

[英]React Native REST API will not convert JSON object to String without displaying [object Object]

問題在於,React Native App顯示將不會顯示存儲在getMovies()中的JSON字符串的內容。 getMovies()中的顯示邏輯無法識別要打印的文本,僅顯示不帶任何內容的[object Object]。

從'react'導入React,{組件}; 從'react-native'導入{Platform,StyleSheet,Text,View};

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<{}> {

  render() {
    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>

        <Text>{getMovies().toString()}</Text>


      </View>


    );
  }
}

function getMovies() {
    var movies = getMoviesFromApiAsync();

    return movies;
}

function getMoviesFromApiAsync() {
    return fetch('https://facebook.github.io/react-native/movies.json')
        .then((response) => response.json())
        .then((responseJson) => {
            return responseJson.movies;
        })
        .catch((error) => {
            console.error(error);
        });
}

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,
  },
});

如果沒有自定義的toString()實現,則在對象上調用toString()將遵循原型鏈,直至對象原型toString方法,該方法將像您所看到的那樣簡單地打印出[object Object]

您可以:

  1. 更換getMovies().toString()JSON.stringify(getMovies())這將讓你更接近你想要什么,但它必須包含字符串大括號內。
  2. getMovies().toString()替換為自定義渲染器,例如Object.values(getMovies()).map(movie => <MovieDetails movie={movie} />) ,您在其中構建了自己的MovieDetails組件。

您可以在這里查看此https://repl.it/repls/RashBowedHarpyeagle

import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
export default class App extends Component<{}> {
   constructor(props){
     super(props)
     this.state = {
      movies: []
     }
   }
  componentDidMount(){
    this.getMovies()
  }  
  getMovies = () => {
    this.getMoviesFromApiAsync()
    .then(movies => {
      console.log(movies)
      this.setState({
        movies
      })
    })
 }
  getMoviesFromApiAsync = () => {
    return fetch('https://facebook.github.io/react-native/movies.json')
        .then(response=> response.json())
        .then(responseJson => responseJson.movies)
        .catch(error => console.error(error));
 }
  render() {
    return (
      <View style={styles.container}>
        {
          this.state.movies.map((movie, index) => {
           return <Text key = {index}>{movie.title}<Text>{movie.releaseYear}</Text></Text>    
          })
        }
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  }
});

這樣做的問題在於,函數getMovies()返回一個promise及其值,直到它被執行后才解析,然后調用then()函數。 這是解決方案:

export default class App extends Component {

  state = {
    movies: [],
  }

  componentDidMount() {
    getMovies().then(movies => this.setState({ movies: movies.map(movie => movie.title).join(', ') }));
  }

  render() {
    const { movies } = this.state;
    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>

        <Text>{movies}</Text>


      </View>


    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM