react-native-Fetch初体验

一:从网络上获取数据,支持POST,GET:

二:发起请求:

fetch('https://www.baidu.com');

三:控制请求方式,headers,body:

fetch('https://www.baidu.com', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

body中传入请求参数,k-v的形式传入:

四:接收返回参数:
使用Promise 异步处理:

fetch('http:www.baidu.com')
      //response.json()是把返回的转换成json格式的对象,response.text()是把返回的数据转化成
       text文本格式
      .then((response) => response.json())
      .then((responseJson) => {
        //responseJson是返回的已经转换成json的数据,可以根据需要取里面的数据
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
  });

五:使用案例:
1-:点击按钮去请求数据,然后获取到返回的数据,把数据更新到text中:
2-:通过浏览器访问此接口:

http://bbs.reactnative.cn/api/coatery/3

可以获取到如下数据:

{"path":"/coatery/3","title":"[[global:404.title]]"}

请求数据代码:

export default class AwesomeProject extends Component {
  constructor(props) {
    super(props);

    this.state = {
      title:'',
    };
  }

   fetchData=(eventCallBack)=>{
   fetch('http://bbs.reactnative.cn/api/coatery/3')
      .then((response) => response.json())
      .then((responseJson) => {
          this.setState({
            title:responseJson.path,
          })

      })
      .catch((error) => {
        console.error(error);
      });
      eventCallBack();
    };


  render() {
    return (
      <View style={{padding:20}}>
        <Text>{this.state.title}</Text>
        <Button  ref="Button"  text='name'   onPress={this.fetchData}/>
    </View>
    );
  }
}

Button是封装的一个组件,可以传递文字,控制按钮颜色,自定义事件!关于Button.js查看上篇博客。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值