react-native的网络访问(Fetch)

####使用Fetch API进行网络访问

Fetch API相关文档地址

示例代码:(引用自react-native中文网

fetch("https://mywebsite.com/endpoint/", 
{
  method: "POST",//"GET"
  headers: {//请求头设置
    Accept: "application/json",
    "Content-Type": "application/json" //form表单提交:application/x-www-form-urlencoded
  },
  body: JSON.stringify({  //请求参数JSON文本格式,也可以是url格式:key1=value1&key2=value2
    key1: "value1",
    key2: "value2"
  })
})
.then(response => response.json()) //response转化为json的对象
.then(responseJson => { //数据处理
  //处理数据
})
.catch(error => {//异常抛出
  console.error(error);
});

then()说明:Promise对象的链式调用。主要用于异步操作后的回调设置,这里是网络访问后的回调。

####相关测试代码

export default class App extends Component {
  constructor(props){
    super(props);
    this.state = {isLoading:true}
  }

  componentDidMount(){ //在react组件装载后加载数据。
    this.setState({isLoading:true});
    return this.getMoviesListDataAsync();
  }

  getMoviesListDataAsync(){
    return fetch("https://facebook.github.io/react-native/movies.json")
      .then(response => response.json())
      .then(responseJsonData => {

        this.setState({
          isLoading:false,
          respData:responseJsonData
        });

      })
      .catch(error =>{
        Alert.alert(error);
        console.error(error);
      })

  }
  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex:1,padding:20}}>
          <ActivityIndicator />
        </View>
      )
    }

    return(
      <View style={{flex:1,padding:20}}>
          <Text>{this.state.respData.title}</Text>
          <Text>{this.state.respData.description}</Text>
          <FlatList 
            data = {this.state.respData.movies}
            renderItem = {({item}) => <Text>电影名称:{item.title},上映年份:{item.releaseYear}</Text>}
            keyExtractor = {(item,index) => index.toString()}
          />
      </View>
    );
  }
}

END

– Nowy

– 2018.10.26

分享到