首先要分别安装两个插件。
命令是:npm install axios --save和npm install fetch-jsonp --save,如果引入了淘宝镜像,可以使用cnpm命令,速度更快。
通过在首页上引入axios和fetch-jsonp来实现插件的使用:
import Axios from ‘./Axios’
import FetchJsonp from ‘./FetchJsonp’
然后后面在render类的return项加入
<Axios />
<FetchJsonp />
下面是两个页面的分别编写:
1、Axios.js:
import React, { Component } from 'react';
import axios from 'axios'
class Axios extends Component {
constructor(props) {
super(props);
this.state = {
list: []
};
}
getData = () => {
var api = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
axios.get(api)
.then((response) => {
// handle success
console.log(response.data.result);
//注意this指向
this.setState({
list: response.data.result
})
})
.catch(function (error) {
// handle error
console.log(error);
})
}
render() {
return (
<div>
<h2>
axios获取服务器数据
</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 Axios;
2、FetchJsonp.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&callback=xxxx'
fetchJsonp(api)
.then((response) => {
return response.json()//json是data的一种数据格式
}).then((json) => {
// console.log('parsed json', json)
this.setState({
list: json.result
})
}).catch((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;
两种不同方式的获取服务器数据。