react-native - 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'
},
});
解决方案
以下行:
this.setState = ({
forecast:response,
hasData:true
})
应该:
this.setState({
forecast:response,
hasData:true
})
您还应该考虑将状态中的预测初始化为空对象。
推荐阅读
- javascript - 如何在没有模板引擎的情况下快速呈现动态 HTML 文件
- jquery - 如何在 asp.net 中对数据进行分组?
- spring - Spring Batch 多线程与 Partitioner
- html - 如何进行 HTML/CSS 定位
- linux - FFmpeg 在给定时间将音频剪辑混合到一个主音频文件中
- scikit-learn - KNeighborsRegressor 和 KNNImputer 有什么区别
- sql - 如何将聚合值分配给 SQL 中同一列上的多个变量?
- r - R:从单个数据帧预测多个时间序列
- tensorflow - 低三重损失精度 CIFAR10
- javascript - React 不会编译我尝试使用 react-pdf 的组件