React学习之旅----axios与fetch-jsonp

父组件

import React from 'react'
import Header from './Header'
import Footer from './Footer'
import Axios from './Axios'
import FetchJsonp from './FetchJsonp'
class Father extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '父组件',
      count: 20
    }
  }
  run = () => {
    alert('我是父组件的run方法')
  }
  getData = () => {
    alert(this.state.title)
  }
  // 获取子组件传过来的数据
  getChildData = (result) => {
    alert(result)
    this.setState({
      title: result
    })
  }
  // 父组件自动调动子组件的方法
  getFooter = () => {
    alert(this.refs.footer.state.title)
    this.refs.footer.run()
  }
  render () {
    return (
      
{/* 父子组件传值: 父组件给子组件传值 1.在调用子组件的时候定义一个属性
2.子组件里面 this.props.msg 说明:父组件不仅可以给子组件传值,还可以给子组件传方法,以及把整个父组件传给子组件。 父组件主动获取子组件的数据 1、调用子组件的时候指定ref的值
2、通过this.refs.header 获取整个子组件实例 dom加载完成后获取*/} {/* 将title传递给子组建 */} {/* 传递父组件的方法 */} {/* 将整个父组件传递过去 */}
{this.state.title}

) } } export default Father

axios.js

import React from 'react'
import axios from 'axios'
class Axios extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list:[]
    };
  }
  getData = () => {
    // alert('ok')
    //通过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 (
      

获取服务器数据


    { this.state.list.map((value,key)=>{ return (
  • {value.title}
  • ) }) }
); } } export default Axios;

fetchJsonp.js

import React from 'react'
import fetchJsonp from 'fetch-jsonp'
class FetchJsonp extends React.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 (
      

FetchJsonp获取服务器jsonp接口的数据


{/* 如何看一个接口支持jsonp,就是在一个接口网址后面加上callback=xxx,只要能获取到数据,就是支持jsonp接口 */}
    { this.state.list.map((value, key) => { return (
  • {value.title}
  • ) }) }
); } } export default FetchJsonp;

 

你可能感兴趣的:(学习笔记)