【发布时间】:2020-05-23 18:29:52
【问题描述】:
我正在从开源 api 获取 json。我想将它存储为一个状态。无法以状态存储 json 数据。我需要使用这个 json 数据来匹配一个城市与 json 中的一个城市。我需要将它存储在状态中。会非常有用。请帮忙!
构造函数部分
constructor(props) {
super(props)
this.state = {
location: null,
loading: false,
userLatitude: null,
userLongitude: null,
userCity: null,
covidZones: []
}
this._requestLocation = this._requestLocation.bind(this)
this.getZone = this.getZone.bind(this)
}
功能部分
getZone() {
axios.get('https://api.covid19india.org/zones.json')
.then(function(response) {
this.setState({
covidZones: response.data.zones
})
})
.catch(function(error) {
// handle error
console.log(error);
})
.finally(function() {
// always executed
})
}
渲染部分
render() {
const { location, loading } = this.state;
return (
<View>
<Button
disabled={loading}
title="Get Location"
onPress={this._requestLocation}
/>
<Text>{this.state.userCity}</Text>
{this.getZone()} // calling the function, right here
{loading ? (
<ActivityIndicator />
) : null}
{location ? (
<Text>
{JSON.stringify(location, 0, 2)}
</Text>
) : null}
</View>
)
}
【问题讨论】:
-
你应该在
componentDidMount()生命周期钩子中运行你的数据获取操作。参考这里:reactjs.org/docs/…
标签: javascript android node.js reactjs react-native