React Native-状态未保存在对象中

时间:2019-03-24 19:37:30

标签: react-native

我正在尝试React Native,现在我正在从openweather API获取天气预报。用户输入城市名称并点击按钮后,数据将被提取。

问题是我试图将对状态对象属性“ forecast”的响应保存,但未保存。

我在做什么错了?

 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.log(response) <-- This is a json reponse with one object
      })
      .catch((error) => {
          console.log("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'
  },
});

Herer is the JSON response frpm openweather API

1 个答案:

答案 0 :(得分:0)

以下行:

spring:
  autoconfigure.exclude: your.package.TestAutoConfiguration 

应为:

this.setState = ({
  forecast:response,
  hasData:true
})

您还应该考虑将预测初始化为空对象。