I use react native on windows with Expo and my iphone 5 with expo app. I wish to get data from a webservice api , with React Native i have this error : App.js: unexpected token(15:6) I wish to get the response array from the webservice
Here is my code :
import React, { Component } from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native'
export default class App extends Component {
fetch('https://httpbin.org/get').then(function (response) {
return response;
}).then(function (response) {
setTimeout(function () {
main.setState({
infoStatus: 'loaded'
});
}, 300);
return response.json();
}).then(function (data) {alert(data);
main.setState({
city: data.name,
country: data.sys.country,
temperature: data.main.temp,
humidity: data.main.humidity,
wind: data.wind.speed
});
}).catch(function () {
main.setState({
infoStatus: 'error'
});
});
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome
</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
})
You may want to put your code into componentDidMount
lifecycle hook.
class App extends Component {
componentDidMount () {
fetch() ...
}
render () {
}
}
What is the object 'main' in your code? and why do you use setTimeout?
you need to put the fetch call inside a method... normally you will do it in componentWillMount for example:
export default class App extends Component {
componentWillMount() {
fetch('https://httpbin.org/get')
.then(function(response) {
this.setState({ infoStatus: 'loaded' });
return response.json();
})
.then(function(data) {
this.setState({
city: data.name,
country: data.sys.country,
temperature: data.main.temp,
humidity: data.main.humidity,
wind: data.wind.speed
});
})
.catch(function () {
main.setState({
infoStatus: 'error'
});
});
}
render() {...}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.