fetch('url'+参数a, { method: "GET", body: json } .then(res => response.json()) .then(console.log(json)) )
一个发送post请求的示例:
fetch("http://127.0.0.1:7777/postContent", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
mode: "cors",
body: JSON.stringify({
content: "留言内容"
})
}).then(function(res) {
if (res.status === 200) {
return res.json()
} else {
return Promise.reject(res.json())
}
}).then(function(data) {
console.log(data);
}).catch(function(err) {
console.log(err);
});
fetch("/students.json")
.then(
function(response){
if(response.status!==200){
console.log("存在一个问题,状态码为:"+response.status);
return;
}
//检查响应文本
response.json().then(function(data){
console.log(data);
});
}
)
.catch(function(err){
console.log("Fetch错误:"+err);
});
- class AwesomeProject extends Component {// 初始化模拟数据
- constructor(props) {
- super(props);
- const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => {r1 !== r2}});
- this.state = {
- dataSource: ds,
- load:false,
- text:''
- };
- }
- //耗时操作放在这里面
- componentDidMount(){
- this.getNet();
- }
- getNet(){
- fetch('http://gank.io/api/search/query/listview/category/福利/count/10/page/1')//请求地址
- .then((response) => response.json())//取数据
- .then((responseText) => {//处理数据
- //通过setState()方法重新渲染界面
- this.setState({
- //改变加载ListView
- load: true,
- //设置数据源刷新界面
- dataSource: this.state.dataSource.cloneWithRows(responseText.results),
- })
- })
- .catch((error) => {
- console.warn(error);
- }).done();
- }
- render() {
- if(this.state.load){
- return (
- <View style={{flex: 1, paddingTop: 22}}>
- <ListView
- dataSource={this.state.dataSource}
- renderRow={(rowData)=>
- <View>
- <Image
- style={{ 400, height: 250, marginTop: 5 }}
- source={{uri:rowData.url}}/>
- </View>}
- />
- </View>
- );
- } else{
- return(
- <View>
- <Text>loading......</Text>
- </View>
- );
- }
- }
- }
项目:
export default class View extends Component {
state = {
total: {},
}
componentDidMount() {
fetch('')
.then((response) => {
return response.json();
})
.then((data) => {
this.setState({total: data.data});
});
}
render() {
const {total: {usersCount, msgsCount}} = this.state;
return (
<div className="user-summary">
<div className="summary-top">
<h1>微信公众号汇总</h1>
<ul>
<li>总关注人数:<span>{usersCount}</span></li>
<li>总消息数:<span>{msgsCount}</span></li>
</ul>
</div>
</div>
);
}
}