/* react獲取服務器APi接口的數據: react中沒有提供專門的請求數據的模塊。但是我們可以使用任何第三方請求數據模塊實現請求數據 1、axios https://github.com/axios/axios axios的作者覺得jsonp不太友好,推薦用CORS方式更為干凈(后端運行跨域) 1、安裝axios模塊npm install axios --save / npm install axios --save 2、在哪里使用就在哪里引入import axios from 'axios' 3、看文檔使用 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); }); 2、fetch-jsonp https://github.com/camsong/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實現數據請求也可以... 遠程測試API接口: get請求: http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20 jsonp請求地址: http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&callback=? */ import React, { Component } from 'react'; import '../assets/css/index.css'; import Axios from './Axios'; class Home extends Component { constructor(props){ super(props); this.state={ title:'首頁組件' } } render() { return ( <div> <Axios /> </div> ); } } export default Home;
方式一:Axios獲取服務器數據:
import React, { Component } from 'react';
import axios from 'axios';
class Axios extends Component {
constructor(props) {
super(props);
this.state = {
list:[]
};
}
getData=()=>{
//通過axios獲取服務器數據
var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20'; //接口后台允許了跨域
axios.get(api)
.then((response)=> {
console.log(response.data.result);
//用到this要注意this指向
this.setState({
list:response.data.result
})
})
.catch(function (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;
方式二:FetchJsonp獲取服務器數據:
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;
