React Native入门技法二

361 阅读3分钟

学习RN第二天,尝试一个移动端的常用功能。请求服务器+返回json+显示列表。我是个从Java转Android的猿,没有js基础,不会Python,上手RN之前看了2天Node.js。如果你也是和我差不对的情况,我的接下来的入门keng指南可能会适合你。   创建完的项目结构是这样的。看起来有一个完整的Android项目目录和IOS项目目录。我用的IDE是VSCode。项目名就叫debug,请不要介意。node_modules是node依赖的库。这次的代码就从index.android.js开始。

结构
  这次要请求的json地址是:https://facebook.github.io/react-native/movies.json

全部代码:


import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Alert,
  Text,
  View,
  FlatList
} from 'react-native';

export default class debug extends Component {
  constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData() {
    fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          movies: responseData.movies,
        });
      })
      .done();
  }
  render() {
    if (!this.state.movies) {
      return this.renderLoadingView();
    }

    return this.renderMovie(this.state.movies);
  }
  renderLoadingView() {
    return (
      <View style={styles.container}>
        <Text>
          Loading movies...
        </Text>
      </View>
    );
  }

  renderMovie(movies) {
    return (
      <View style={styles.container}>
       <FlatList
          data={movies}
          renderItem={({item}) => <Text style={styles.item}>{item.title},发行于{item.releaseYear}年</Text>}
        />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  item: {
    padding: 10,
    fontSize: 18,
    height: 44,
  },
});

AppRegistry.registerComponent('debug', () => debug);

下面说一下代码的意思:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Alert,
  Text,
  View,
  FlatList
} from 'react-native';

这里就是最常见的引入操作啦,要注意的是如果你要用到Button,Image啊什么的,就需要在这里引入,这次用到的是Text显示一个文本,和FlatList列表,相当于Android原声的ListView,这个东西的好处是屏幕之外的不会被渲染,节省资源(官网是这么说的)。好啦不重要啦。

###知识点一:props和state props是在父组件中指定,而且一经指定,在被指定的组件的生命周期中则不再改变。 对于需要改变的数据,我们需要使用state。

constructor(props) {
    super(props);
    this.state = {
      movies: null,
    };
  }

在state里面放了一个movies,用于存放数据。

###知识点二:生命周期

componentDidMount() {
    this.fetchData();
  }

我们在第一遍渲染完成之后,请求网络数据。所有的网络动作推荐在componentDidMount中完成。 componentDidMount()这个方法会在render()渲染之后被调用。

生命周期

个人理解:

上面的那个虚线框就相当于oncreate走完了。   当props变化了之后,componentWillReceiveProps()被调用,在这个方法里面可以修改state,然后调用shouldComponentUpdate()返回是否需要更新界面,如果不需要返回false,componentWillUpdate和componentDidUpdate方法也不会被调用。这里默认是返回true的。   当组件要被从界面上移除的时候,就会调用componentWillUnmount(),在这个函数中,可以做一些组件相关的清理工作,例如取消计时器、网络请求等。   建议只在componentWillMount,componentDidMount,componentWillReceiveProps方法中修改state。

###知识点三:网络请求 这里就是请求数据。

fetchData() {
    fetch('https://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseData) => {
        this.setState({
          movies: responseData.movies,
        });
      })
      .done();
  }

fetch貌似是RN原生网络请求方法。而且是异步的!!!这里还用到了promise,具体promise是啥,我看了一边网上的教程,感觉就是回调,具体是啥不明白。fetch返回的就是promise对象,promise对象根据不同的状态会走then。这里就是2个then依次走的。然后把数据赋值给state。

render() {
    if (!this.state.movies) {
      return this.renderLoadingView();
    }

    return this.renderMovie(this.state.movies);
  }

这里就是根据state中movies的状态,调用不同的具体的渲染方法。这里着重说所renderMovie

###知识点四:FlatList FlatList有2个属性data用于存放数据,renderItem用于渲染。

renderMovie(movies) {
    return (
      <View style={styles.container}>
       <FlatList
          data={movies}
          renderItem={({item}) => <Text style={styles.item}>{item.title},发行于{item.releaseYear}年</Text>}
        />
      </View>
    );
  }

=>这个箭头之前的是参数列表,后面的是返回值,相当于一种函数的简写方式,就像lamda吧,是ES6的新特性。item就是data中的每项数据的遍历。

效果