我正在从开源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>
)
}
I have prepared an example for your using
reactjs
. Same technic should be followed inreact-native
. Please follow this example:这是输出中的图像
You are calling an api
{this.getZone()}
in therender
function. This, I'm afraid, will lead to an infinite loop as after each of those calls,setState
will be triggered which in turn will call therender
function.To fix this: 1. Remove
{this.getZone()}
fromrender
method. 2. Put this incomponentDidMount