【问题标题】:No Data presenting to screen in React NativeReact Native 中没有数据显示在屏幕上
【发布时间】:2020-07-24 10:31:31
【问题描述】:

我正在尝试在 React Native 中做一个简单的第一个应用程序。我在 App.js 中有一个带有按钮的简单主屏幕,点击按钮并显示数据。数据保存在 mongodb 中,springboot 用于 api。我正在运行弹簧靴并与邮递员进行测试。这是工作。我将 app.js,列表组件放在 src 文件夹中,然后是我正在尝试使用的 mongodb 数据的 sn-p。我只是不确定为什么数据没有显示在屏幕上。

App.js

import React, {Component} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import {Listings} from './src/Listings';

type Props = {};
export default class App extends Component<Props> {
  render() {
    return (
      <View style={{flex: 1}}>
        <Text style={styles.welcome}>Air BNB Data Screen</Text>
        <View style={{flex: 1, borderWidth: 3, borderColor: 'blue'}}>
          <Listings></Listings>
        </View>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

源代码 Listings.js

import React from 'react';
import {View, Button} from 'react-native';
import axios from 'axios';

export class Listings extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
      listings: [],
    };
  }

  getlistings = () => {
    const options = {
      headers: {'Content-Type':'application/json'}
    }
    axios.get('http://localhost:8080/api/Listings/10006546', options)
      .then(response => response.data())
      .then(json => {
        console.log(json);
        if (json.error) return false;
      })
      .catch(error => {
        console.log(error);
      });
  };


  render() {
    return (
      <View style={{flex: 1, borderWidth: 3, borderColor: 'yellow'}}>
        <Button
          style={{flex: 1, borderWidth: 3, borderColor: 'red'}}
          title={'listings'}
          onPress={()=>{this.getlistings()}}
        />
      </View>
    );
  }
}

Mongodb - 这是邮递员 GET 请求

{
    "_id": "10006546",
    "listing_url": "https://www.airbnb.com/rooms/10006546",
    "name": "Ribeira Charming Duplex",
    "summary": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube) - UNESCO World Heritage Site. Centenary building fully rehabilitated, without losing their original character.",
    "space": "Privileged views of the Douro River and Ribeira square, our apartment offers the perfect conditions to discover the history and the charm of Porto. Apartment comfortable, charming, romantic and cozy in the heart of Ribeira. Within walking distance of all the most emblematic places of the city of Porto. The apartment is fully equipped to host 8 people, with cooker, oven, washing machine, dishwasher, microwave, coffee machine (Nespresso) and kettle. The apartment is located in a very typical area of the city that allows to cross with the most picturesque population of the city, welcoming, genuine and happy people that fills the streets with his outspoken speech and contagious with your sincere generosity, wrapped in a only parochial spirit.",
    "description": "Fantastic duplex apartment with three bedrooms, located in the historic area of Porto, Ribeira (Cube) - UNESCO World Heritage Site. Centenary building fully rehabilitated, without losing their original character. Privileged views of the Douro River and Ribeira square, our apartment offers the perfect conditions to discover the history and the charm of Porto. Apartment comfortable, charming, romantic and cozy in the heart of Ribeira. Within walking distance of all the most emblematic places of the city of Porto. The apartment is fully equipped to host 8 people, with cooker, oven, washing machine, dishwasher, microwave, coffee machine (Nespresso) and kettle. The apartment is located in a very typical area of the city that allows to cross with the most picturesque population of the city, welcoming, genuine and happy people that fills the streets with his outspoken speech and contagious with your sincere generosity, wrapped in a only parochial spirit. We are always available to help guests",
    "neighborhood_overview": "In the neighborhood of the river, you can find several restaurants as varied flavors, but without forgetting the so traditional northern food. You can also find several bars and pubs to unwind after a day's visit to the magnificent Port. To enjoy the Douro River can board the boats that daily make the ride of six bridges. You can also embark towards Régua, Barca d'Alva, Pinhão, etc and enjoy the Douro Wine Region, World Heritage of Humanity. The Infante's house is a few meters and no doubt it deserves a visit. They abound grocery stores, bakeries, etc. to make your meals. Souvenir shop, wine cellars, etc. to bring some souvenirs.",
    "notes": "Lose yourself in the narrow streets and staircases zone, have lunch in pubs and typical restaurants, and find the renovated cafes and shops in town. If you like exercise, rent a bicycle in the area and ride along the river to the sea, where it will enter beautiful beaches and terraces for everyone. The area is safe, find the bus stops 1min and metro line 5min. The bustling nightlife is a 10 min walk, where the streets are filled with people and entertainment for all. But Porto is much more than the historical center, here is modern museums, concert halls, clean and cared for beaches and surf all year round. Walk through the Ponte D. Luis and visit the different Caves of Port wine, where you will enjoy the famous port wine. Porto is a spoken city everywhere in the world as the best to be visited and savored by all ... natural beauty, culture, tradition, river, sea, beach, single people, typical food, and we are among those who best receive tourists, confirm! Come visit us and feel at ho",
    "transit": "Transport: • Metro station and S. Bento railway 5min; • Bus stop a 50 meters; • Lift Guindais (Funicular) 50 meters; • Tuc Tuc-to get around the city; • Buses tourist; • Cycling through the marginal drive; • Cable car in Gaia, overlooking the Port (just cross the bridge).",
    "access": "We are always available to help guests. The house is fully available to guests. We are always ready to assist guests. when possible we pick the guests at the airport.  This service transfer have a cost per person. We will also have service \"meal at home\" with a diverse menu and the taste of each. Enjoy the moment!",
    "interaction": "Cot - 10 € / night Dog - € 7,5 / night",
    "house_rules": "Make the house your home...",
    "property_type": "House",
    "room_type": "Entire home/apt",
    "bed_type": "Real Bed",
    "minimum_nights": "2",
    "maximum_nights": "30",
    "cancellation_policy": "moderate",
    "last_scraped": "2019-02-16T05:00:00.000+0000",
    "calendar_last_scraped": "2019-02-16T05:00:00.000+0000",
    "first_review": "2016-01-03T05:00:00.000+0000",
    "last_review": "2019-01-20T05:00:00.000+0000",
    "accommodates": 8,
    "bedrooms": 3,
    "beds": 5,
    "number_of_reviews": 51,
    "bathrooms": 1.0,
    "amenities": [
        "TV",
        "Cable TV",
        "Wifi",
        "Kitchen",
        "Paid parking off premises",
        "Smoking allowed",
        "Pets allowed",
        "Buzzer/wireless intercom",
        "Heating",
        "Family/kid friendly",
        "Washer",
        "First aid kit",
        "Fire extinguisher",
        "Essentials",
        "Hangers",
        "Hair dryer",
        "Iron",
        "Pack ’n Play/travel crib",
        "Room-darkening shades",
        "Hot water",
        "Bed linens",
        "Extra pillows and blankets",
        "Microwave",
        "Coffee maker",
        "Refrigerator",
        "Dishwasher",
        "Dishes and silverware",
        "Cooking basics",
        "Oven",
        "Stove",
        "Cleaning before checkout",
        "Waterfront"
    ],
    "price": 80.00,
    "security_deposit": 200.00,
    "cleaning_fee": 35.00,
    "extra_people": 15.00,
    "guests_included": 6,
    "images": {
        "thumbnail_url": "",
        "medium_url": "",
        "picture_url": "https://a0.muscache.com/im/pictures/e83e702f-ef49-40fb-8fa0-6512d7e26e9b.jpg?aki_policy=large",
        "xl_picture_url": ""
    }

【问题讨论】:

    标签: javascript react-native axios fetch-api


    【解决方案1】:

    在您的代码中,您犯了两个错误。

    1) 虽然您已经初始化了状态“listings”,但您还没有将响应数据分配给 Listings 状态。您可以按如下方式分配它。

     getlistings = () => {
        const options = {
          headers: {'Content-Type':'application/json'}
        }
        axios.get('http://localhost:8080/api/Listings/10006546', options)
          .then(response => {
    
            this.setState({
             listings:response.data()
             });
    
    
          })
          .catch(error => {
            console.log(error);
          });
      };
    

    2) 您还没有编写任何方式(DOM 元素)来查看列表数组中的数据。例如:表格、列表等

    希望以下链接能帮助您了解如何在 React-Native 中显示 json 数组

    https://www.reddit.com/r/reactnative/comments/bs0lzt/display_nested_json_array_data_within_flatlist/

    【讨论】:

    • 你必须包含一个显示数据的方法。为此,请点击我包含的链接。在此之前,请对“getlistings”方法进行我提到的必要更改。谢谢你。希望这会有所帮助
    • 您能否进一步解释一下。我对 React Native 很陌生。当我拿走你的代码时,它会在代码中抛出错误。然后我去了建议的链接,并没有理解。它看起来更像是一个反应设置而不是 React Native 设置
    • 第一个错误,您必须将响应分配给状态变量“列表”,您可以通过以下代码执行此操作。 this.setState({ Listings:response.data })
    • 第二个错误假设您已将响应值正确分配给“lisitngs”状态变量。然后您必须使用平面列表或任何其他方式显示该数据。请使用更新的链接以平面列表显示 json 数组数据。希望这会有所帮助
    • 抱歉,getlistings() 方法中有错字。我已经解决了。 (失踪 ”{” )。使用该方法并使用教程显示 json 数据。希望这会有所帮助
    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多