Изменение данных в проекте React Native - PullRequest
0 голосов
/ 01 мая 2020

Я создаю реактивный собственный проект, который дает пользователю обновленную информацию о ситуации с COVID-19, используя «https://covid19.mathdro.id/api», приложение по умолчанию возвращает глобальный счетчик, а затем пользователь может выбрать страну и получить для нее указанную c информацию, я смотрел учебник на YouTube, но у меня, как у новичка, есть проблема, я делаю кнопки для названий стран вместо выбора и выбора, но когда выбираю определенную страна, количество не меняется, и я не получаю ошибок. вот код: `

import Axios from "axios";
import * as React from 'react';
// import { OptionsButton } from 'react-native-options-button';
import { Image, Platform, StyleSheet, Text, TouchableOpacity, View, Alert, Button, ScrollView } from 'react-native';
class HomeScreen extends React.Component {

  constructor(props) {
    super(props);

    this.getCountryData = this.getCountryData.bind(this);
  }
  state = {
    confirmed: 0,
    recovered: 0,
    deaths: 0,
    countries: [],
  }
  //We set a state with initial values that we can change later on after we get the 
  //proper info using the SetState method.
  componentDidMount() {
    this.getData();
  }
  //Automatically calls this function:
  async getData() {
    const resAPI = await Axios.get("https://covid19.mathdro.id/api")
    const resCountries = await Axios.get("https://covid19.mathdro.id/api/countries");
    const countries = [];
    for (var i = 0; i < resCountries.data.countries.length; i++) {
      countries.push(resCountries.data.countries[i].name);
    }


    this.setState({
      confirmed: resAPI.data.confirmed.value,
      recovered: resAPI.data.recovered.value,
      deaths: resAPI.data.deaths.value,
      countries
      //changes the original state of countries which i an empty array to the new state 
      //which has the key for each country.
    })
  }
  async getCountryData(event) {
    const res = await Axios.get("https://covid19.mathdro.id/api/countries/NL/" + event.target.value);
    this.setState({
      confirmed: res.data.confirmed.value,
      recovered: res.data.recovered.value,
      deaths: res.data.deaths.value
    })
  }
  rendercountryoptions() {
    return this.state.countries.map((name, i) => {
      return <Button title={name} onPress={this.getCountryData} value={name} key={name} />
    });
  }
  //Async function because it is waiting (await) for a promise to be applied which is 
  // for axios to get the info in the link, then get the specific data needed.
  render() {
    return (
      <ScrollView >
        <Text>Corona Update</Text>
        <Text>Confirmed cases </Text>
        <Text>{this.state.confirmed}</Text>
        <Text>Recovered cases</Text>
        <Text>{this.state.recovered}</Text>
        <Text>Death cases</Text>
        <Text>{this.state.deaths}</Text>
        {this.rendercountryoptions()}
      </ScrollView>
    )
  }
}
export default HomeScreen

`

Ответы [ 2 ]

0 голосов
/ 01 мая 2020

Работает, проверено:

import Axios from "axios";
import * as React from 'react';
// import { OptionsButton } from 'react-native-options-button';
import { Image, Platform, StyleSheet, Text, TouchableOpacity, View, Alert, Button, ScrollView } from 'react-native';
class HomeScreen extends React.Component {

  constructor(props) {
    super(props);

    this.getCountryData = this.getCountryData.bind(this);
  }
  state = {
    confirmed: 0,
    recovered: 0,
    deaths: 0,
    countries: [],
  }
  //We set a state with initial values that we can change later on after we get the
  //proper info using the SetState method.
  componentDidMount() {
    this.getData();
  }
  //Automatically calls this function:
  async getData() {
    const resAPI = await Axios.get("https://covid19.mathdro.id/api")
    const resCountries = await Axios.get("https://covid19.mathdro.id/api/countries");
    const countries = [];
    for (var i = 0; i < resCountries.data.countries.length; i++) {
      countries.push(resCountries.data.countries[i].name);
    }


    this.setState({
      confirmed: resAPI.data.confirmed.value,
      recovered: resAPI.data.recovered.value,
      deaths: resAPI.data.deaths.value,
      countries
      //changes the original state of countries which i an empty array to the new state
      //which has the key for each country.
    })
  }
  async getCountryData(name) {
    const res = await Axios.get("https://covid19.mathdro.id/api/countries/" + name);
    this.setState({
      confirmed: res.data.confirmed.value,
      recovered: res.data.recovered.value,
      deaths: res.data.deaths.value
    })
  }
  rendercountryoptions() {
    return this.state.countries.map((name, i) => {
      return <Button title={name} onPress={() => this.getCountryData(name)} value={name} key={name} />
    });
  }
  //Async function because it is waiting (await) for a promise to be applied which is
  // for axios to get the info in the link, then get the specific data needed.
  render() {
    return (
      <ScrollView >
        <Text>Corona Update</Text>
        <Text>Confirmed cases </Text>
        <Text>{this.state.confirmed}</Text>
        <Text>Recovered cases</Text>
        <Text>{this.state.recovered}</Text>
        <Text>Death cases</Text>
        <Text>{this.state.deaths}</Text>
        {this.rendercountryoptions()}
      </ScrollView>
    )
  }
}
export default HomeScreen
0 голосов
/ 01 мая 2020

Попробуйте:

onPress={() => this.getCountryData({name})}

И

async getCountryData({name})

Кроме того, свяжите все другие методы в конструкторе. Кроме того, getData и getCountryData должны быть в одном методе, а не повторять ваш код.

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