Я пробую React Native и теперь получаю прогноз погоды из openweather API. данные извлекаются после того, как пользователь вводит город и нажимает кнопку.
Проблема в том, что я пытаюсь сохранить ответ на свойство объектов состояния «прогноз», но он не сохраняется.
Что я делаю неправильно?
import React, {Component} from 'react';
import {StyleSheet, Text ,TextInput, View, Button} from 'react-native';
export default class App extends Component {
constructor(props){
super(props);
this.state = {
text:"",
forecast:null,
hasData: false
}
}
userTextChange = (input) => {
this.setState({
text:input
})
}
getMovies = () => {
var url = 'https://api.openweathermap.org/data/2.5/weather?q='+this.state.text+'&units=metric&appid=7d6b48897fecf4839e128d90c0fa1288';
fetch(url)
.then((response) => response.json())
.then((response) => {
this.setState = ({
forecast:response,
hasData:true
})
console.info(response) <-- This is a json reponse with one object
})
.catch((error) => {
console.info("Error: ",error);
});
}
render() {
return (
<View style = {styles.container} >
<TextInput
style = {{width:'80%',borderRadius:8,marginTop:70,height:60,backgroundColor:'#f1f1f1',textAlign:'center',borderWidth:1,borderColor:'#ccc'}}
placeholder = ""
onChangeText = {this.userTextChange}
/>
<Button
title = "Get forecats"
style = {{backgroundColor:'#000',height:50,width:'50%',marginTop:30,marginBottom:30}}
onPress = {()=>this.getMovies()}
/>
<View style = {{width:'90%',height:'68%', backgroundColor:'rgba(0,0,0,0.5)',alignItems:'center',paddingTop:20}}>
<Text style = {{color:'#000',fontSize:22}}>{this.state.forecast.name}</Text> <-- THIS IS NULL
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
alignItems:'center'
},
});





Следующая строка:
this.setState = ({
forecast:response,
hasData:true
})
должно быть:
this.setState({
forecast:response,
hasData:true
})
Вам также следует рассмотреть возможность инициализации прогноз в состоянии пустым объектом.
прогноз не может быть нулевым, когда вы его инициализируете, потому что вы используете
this.state.forecast.name