React Native填坑之旅--HTTP请求篇
React Native填坑之旅--Button篇 如果不能从头到尾的建立一个RN应用,那么RN将失色不少。本以为HTTP请求部分需要使用Native的实现,Android和iOS各回各家,各调各库了。Google了一下之后居然RN可以使用fetch库。这个库是用来代替流传已久的XHR的。 下面看看如何使用fetch 请求Restful API的。API是dribbble的。这个API需要注册,所以如果你要运行下面的例子的话,最好注册一下,或者换一个站点的API试试。 随着ES6,JavaScript内置的支持了Promise这个填补回调地狱大坑的功能。fetch很好的利用了这一点,它的请求返回结果就是Promise。所以,bye回调。 fetch的使用非常简单,比现在流行的任何Native库都好用。 fetch('https://api.dribbble.com/v1/shots',init) .then((response) => response.json()) .then((responseJson) => { this.setState({message: `${responseJson[0].id} - ${responseJson[0].title}`}); }) .catch(e => {console.log(`error ${e}`)}); 其中的init是一个Object或者说是一个字典,里面包含了关于请求方式是GET或者POST等的信息。看起来是这样的: const init = { method: 'GET',headers: { 'Accept': 'application/json','Content-Type': 'application/json','Authorization': '需要认证数据',},}; 请求发出之后,在第一个 在第二个 最后,使用一个 更新界面上面提到的都是如何使用fetch请求的。如果你注意代码的话就会发现里面已经包含了如何更新界面的部分。这里在详细解释一下。 在 this.setState({message: `${responseJson[0].id} - ${responseJson[0].title}`}); 那么组件就会根据state值更新组件: <Text style={{marginTop: 10}}>{this.state.message ? this.state.message : "Empty"}</Text> 是不是非常简单。 全部代码import React from 'react'; import { View,Alert,Text } from 'react-native'; import Button from '../view/touchableButton'; export default class HomeController extends React.Component { constructor(props) { super(props); this.state = { message: '' }; this.fetchAction = this.fetchAction.bind(this); } componentDidMount() { } fetchAction() { this.setState({message: 'Empty'}); const init = { method: 'GET','Authorization': '需要认证',// body: JSON.stringify({ // // }) }; fetch('https://api.dribbble.com/v1/shots',init) .then((response) => response.json()) .then((responseJson) => { this.setState({message: `${responseJson[0].id} - ${responseJson[0].title}`}); }) .catch(e => {console.log(`error ${e}`)}); } render() { return ( <View style={{flex: 1,marginTop: 100,alignItems: 'center'}}> <Button style={{marginTop: 50}} buttonTitle='Click to fetch' onFetch={this.fetchAction} /> <Text style={{marginTop: 10}}>{this.state.message ? this.state.message : "Empty"}</Text> </View> ); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |