1.安装模块 npm install axios --save / npm install fetch-jsonp --save
2.在使用的页面引入
import axios from ‘axios‘
import fetchJsonp from ‘fetch-jsonp‘;
axios
import React from ‘react‘ import axios from ‘axios‘ class Axios extends React.Component{ constructor(props) { super(props) } getData=()=>{ var api=‘http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20‘; //接口后台允许了跨域 alert(1) axios.get(api) .then((res)=>{ console.log(res) }).catch(()=>{}) } render() { return( <div> <button onClick={this.getData}>点击获取接口数据</button> </div> ) } } export default Axios
fetch-jsonp
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;