首页 > 解决方案 > React Native - 状态未保存在对象中

问题描述

我正在尝试 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.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'
  },
});

这里是 JSON 响应 frpm openweather API

标签: react-native

解决方案


以下行:

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

应该:

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

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


推荐阅读