react没有提供自己的请求数据的模块,笔者以axios和fetch-jsonp为例来请求数据。
一、axios
1、安装axios模块
npm install axios --save
引包:
import axios from 'axios'
2、使用
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20';
axios.get(api)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
(这个api是测试用的api,实际可换成自己的api)
代码实现:
import React, {Component} from 'react';
import axios from 'axios'
class Axios extends Component {
constructor(props) {
super(props);
this.state = {
msg:'首页组件',
list:[]
};
}
getData=()=>{
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20'; //接口后台允许了跨域
axios.get(api)
.then((response)=> {
console.log(response.data.result);
//用到this要注意this指向,一般先打印一下接口的后台数据是什么,方便调用,比如这里的后台有用数据是title,pic。
this.setState({
list:response.data.result
})
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<div>
Axios获取组件数据
<button onClick={this.getData}>获取服务器api接口</button>
<ul>
{
this.state.list.map((value,key)=>{
return <li key={key}>{value.title}</li>
})
}
</ul>
</div>
);
}
}
export default Axios;
二、fetch-jsonp
1、安装 npm install fetch-jsonp --save
2、import fetchJsonp from 'fetch-jsonp'
3、看文档使用
fetchJsonp('/users.jsonp')
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})
3、其他请求数据的方法也可以...自己封装模块用原生js实现数据请求也可以...
代码实现:
import React, { Component } from 'react';
import fetchJsonp from 'fetch-jsonp';
class FetchJsonp extends Component {
constructor(props) {
super(props);
this.state = {
list:[]
};
}
getData=()=>{
//获取数据
var api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
fetchJsonp(api)
.then(function(response) {
return response.json()
}).then((json)=> {
// console.log(json);
this.setState({
list:json.result
})
}).catch(function(ex) {
console.log('parsing failed', ex)
})
}
render() {
return (
<div>
<h2>FetchJsonp 获取服务器jsonp接口的数据</h2>
<button onClick={this.getData}>获取服务器api接口数据</button>
<hr />
<ul>
{
this.state.list.map((value,key)=>{
return <li key={key}>{value.title}</li>
})
}
</ul>
</div>
);
}
}
export default FetchJsonp;
总结:当代码报错的时候,怀疑接口本身有问题,可以F12审查代码,netwoprk查看接口,如果浏览器能打开,则接口没问题,需要注意自己写的代码了。