ReactNative网络请求
1.GET请求
requestToTest() {
return fetch(apiURL, {
method: 'GET',
})
.then((response) => response.json())
.then((data) => {
console.log(data);
return data;
}).catch((err) => {
console.log(err);
});
}
2.POST请求
requestToGetApplyId() {
return fetch(apiURL, {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'name': 'userName',
'telephone': '18088888888'
})
})
.then((response) => response.json())
.then((data) => {
console.log(data);
return data;
}).catch((err) => {
console.log(err);
});
}
3.PUT请求
requestToLogin(account, password) {
return fetch(apiURL, {
method: 'PUT',
headers: {
'Accept': 'application/json',
"Content-Type": "application/x-www-form-urlencoded"
},
body: `userName=${userName}&passWord=${passWord}`
})
.then((response) => response.json())
.then((data) => {
console.log(data);
return data;
}).catch((err) => {
console.log(err);
案例:
import React, {Component} from 'react';
import {
StyleSheet,
Text,
Image,
View
} from 'react-native';
var REQUEST_URL =
"https://raw.githubusercontent.com/facebook/react-native/0.51-stable/docs/MoviesExample.json";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
movies: null,
};
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
movies: responseData.movies,
});
});
}
render() {
if(!this.state.movies) {
return this.renderLoadingView();
}
var movie = this.state.movies[0];
return this.renderMovie(movie);
}
renderLoadingView() {
return (
<View style = {styles.container}>
<Text>loading...</Text>
</View>
);
}
renderMovie(movie) {
return(
<View style = {styles.container}>
<Image
style = {styles.thumbnail}
source = {{uri: movie.posters.thumbnail}}
/>
<View style = {styles.rightContainer}>
<Text style = {styles.title}>{movie.title}</Text>
<Text style = {styles.year}>{movie.year}</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
thumbnail: {
width: 100,
height: 80
},
rightContainer: {
flex: 1
},
title: {
fontSize: 20,
marginBottom: 8,
textAlign: 'center'
},
year: {
textAlign:'center'
}
});
评论区