Нет данных для отображения в React Native - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь сделать простое первое приложение в React Native. У меня есть простой домашний экран с кнопкой в ​​приложении. js, нажмите кнопку и представьте данные. Данные хранятся в mongodb, а springboot используется для API. У меня есть весенний ботинок, и у меня тест с почтальоном. Это работает. Я помещу app. js, компонент для списков в папку sr c, а затем фрагмент данных mongodb, с которыми я пытаюсь работать. Я просто не уверен, почему данные не отображаются на экране.

Приложение. 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,
  },
});

src 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 Request

{
    "_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": ""
    }

1 Ответ

0 голосов
/ 11 апреля 2020

В вашем коде вы сделали две ошибки.

1) Несмотря на то, что вы инициализировали состояние «списки», вы не присвоили данные ответа состоянию «списки». Вы можете назначить его следующим образом.

 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) для просмотра данных в массиве списков. Пример: таблица, список и т. Д. c.

Надеюсь, что следующая ссылка поможет вам получить представление об отображении json массивов в React-Native

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...