一:从网络上获取数据,支持POST,GET:
二:发起请求:
fetch('https://www.baidu.com');
三:控制请求方式,headers,body:
fetch('https://www.baidu.com', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
body中传入请求参数,k-v的形式传入:
四:接收返回参数:
使用Promise 异步处理:
fetch('http:www.baidu.com')
//response.json()是把返回的转换成json格式的对象,response.text()是把返回的数据转化成
text文本格式
.then((response) => response.json())
.then((responseJson) => {
//responseJson是返回的已经转换成json的数据,可以根据需要取里面的数据
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
五:使用案例:
1-:点击按钮去请求数据,然后获取到返回的数据,把数据更新到text中:
2-:通过浏览器访问此接口:
http://bbs.reactnative.cn/api/coatery/3
可以获取到如下数据:
{"path":"/coatery/3","title":"[[global:404.title]]"}
请求数据代码:
export default class AwesomeProject extends Component {
constructor(props) {
super(props);
this.state = {
title:'',
};
}
fetchData=(eventCallBack)=>{
fetch('http://bbs.reactnative.cn/api/coatery/3')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
title:responseJson.path,
})
})
.catch((error) => {
console.error(error);
});
eventCallBack();
};
render() {
return (
<View style={{padding:20}}>
<Text>{this.state.title}</Text>
<Button ref="Button" text='name' onPress={this.fetchData}/>
</View>
);
}
}
Button是封装的一个组件,可以传递文字,控制按钮颜色,自定义事件!关于Button.js查看上篇博客。