美文网首页
React-native之仿异步获取网络数据(13)

React-native之仿异步获取网络数据(13)

作者: 飞奔的小马 | 来源:发表于2017-01-30 20:35 被阅读54次
    一. 简介

    应用中不可避免会请求到网络,原生android开发会使用handler机制,通过异步任务AsyncTask请求网络,React-native擅长界面处理,通过this.state来触发。

    二. 示例

    var REQUEST_URL = 'https://raw.githubusercontent.com/facebook/react-native/master/docs/MoviesExample.json';
    class HomeUI extends Component {
    constructor(props) { super(props);//这一句不能省略,照抄即可 this.state = { movies: null, //这里放你自己定义的state变量及初始值 }; }
    render(){ if (!this.state.movies) { //如果movies==null的情况 初始情况 渲染加载视图 return this.renderLoadingView(); } //从网络上获取了数据的情况 var movie = this.state.movies[0]; return this.renderMovie(movie); }
    renderLoadingView() { return ( <View style={styles.container}> <Text> 正在网络上获取电影数据…… </Text> </View> ); }
    renderMovie(movie) { return ( <View style={styles.container}> <Image source={{uri: movie.posters.thumbnail}} style={styles.thumbnail} /> <View style={styles.rightContainer}> <Text style={styles.title}>标题:{movie.title}</Text> <Text style={styles.year}>{movie.year}年</Text> </View> </View> ); } componentDidMount() { this.fetchData(); } fetchData() { fetch(REQUEST_URL) .then((response) => response.json()) .then((responseData) => { this.setState({ movies: responseData.movies, }); }) .done(); //调用了done() —— 这样可以抛出异常而不是简单忽略 } }

    const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, thumbnail: { width: 53, height: 81, }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, });

    效果

    fetchdata_01.png

    相关文章

      网友评论

          本文标题:React-native之仿异步获取网络数据(13)

          本文链接:https://www.haomeiwen.com/subject/yeyhittx.html