ReactNative學習筆記1

一、react-native的生命周期

1. getDefaultProps

在組件創(chuàng)建之前,會先調用 getDefaultProps() ,全局調用一次,嚴格地來說,這不是組件的生命周期的一部分。在組件被創(chuàng)建并加載候,首先調用 getInitialState() ,來初始化組件的狀態(tài)。

2. componentWillMount

準備加載組件

3. render

加載組件

4. componentDidMount

組件第一次加載完成后調用

5. componetWillReceiveProps

當組件收到新的屬性,調用此方法

6. shouldComponentUpdate

這個函數的返回值決定是否需要更新組件,如果 true 表示需要更新,繼續(xù)走后面的更新流程。否者,則不更新,直接進入等待狀態(tài)。

默認情況下,這個函數永遠返回 true 用來保證數據變化的時候 UI 能夠同步更新。在項目中,你可以自己重載這個函數,通過檢查變化前后屬性和狀態(tài),來決定 UI 是否需要更新,能有效提高應用性能。

7. componentWillUpdate

當組件狀態(tài)或者屬性改變,并且上面的 shouldComponentUpdate(...) 返回為 true ,就會開始準更新組件,并調用 componentWillUpdate()。

需要特別注意的是,在這個函數里面,你就不能使用 this.setState 來修改狀態(tài)。這個函數調用之后,就會把 nextProps 和 nextState 分別設置到 this.props 和 this.state 中。緊接著這個函數,就會調用 render() 來更新界面了。

8. componentDidUpdate

在render()之后調用此方法來得到通知

9. componentWillUnmount()

當組件要被界面移除時,調用此方法。在這個方法可以做相關清理工作。

二、props和state

props、state共同來控制組件數據。props是在父組件中指定,而且一經指定,在被指定的組件的生命周期中則不再改變。 對于需要改變的數據,我們需要使用state。

  • props:大多數組件在創(chuàng)建時就可以使用各種參數來進行定制。用于定制的這些參數就稱為props(屬性)。屬性定義時要將屬性名掛載在this.props對象上,其他組件調用該組件時,需要指定該屬性的value。

使用示例:

//在被調用組件中,定義property屬性
export default class PropertyView extends Component{
    
    render(){
        var property =this.props.property;
        var stats= property.bedroom_number+'bed'+property.property_type;
        if (property.bathroom_number){
            stats+=', '+property.bathroom_number+' '+(property.bathroom_number>1
                    ?'bathrooms':'bathroom');
        }

        var price =property.price_formatted.split(' ')[0];

        return(
            <View style={styles.container}>
                <Image style={styles.image}
                source={{uri:property.image_url}}
                />
                <View style={styles.heading}>
                    <Text style={styles.price}>£{price}</Text>
                    <Text style={styles.title}>{property.title}</Text>
                    <Text style={styles.description}>{property.summary}</Text>
                </View>
            </View>
        )
    }
}

//調用組件中為property屬性賦值
this.props.navigator.push({
            title:"PropertyView",
            component:PropertyView,
            passProps:{
               property:property
            }
        });
  • state:在constructor中初始化state,然后在需要修改時調用setState方法。

使用示例:

//在constructor中初始化
constructor(props) {
        super(props);
        this.state = {
            message: ''
        };
    }

//在需要更新數據的位置
this.setState({
    message: 'there was a problem with obtaining your location: ' + error
});

三、navigator

安卓中使用Navigator,IOS使用NavigatorIOS

使用示例:

1.在父組件render()中

render() {
    return (
        <Navigator
            initialRoute={{
                title:'Property Finder'
            }}
            renderScene={(route,navigator)=>{
                return<SearchPage/>
            }}

        />
    );
  }

2.在子組件中使用this.props.navigator獲得navigator,
并且可以通過push和pop方法來推入或彈出component

this.props.navigator.push({
                title: 'Results',
                component: SearchResults,
                passProps: {
                    //向要推入組件傳遞數據
                    listings: response.listings
                }
            });

四、ListView

  • dataSource:列表的數據源
  • renderRow:逐個解析數據源中的數據,然后返回一個設定好格式的組件來渲染。
  • rowHasChanged:必須屬性,比較兩個item數據

使用示例:

class ListViewBasics extends Component {
  // 初始化模擬數據
  constructor(props) {
    super(props);
    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows([
        'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
      ])
    };
  }
  render() {
    return (
      <View style={{flex: 1, paddingTop: 22}}>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text>{rowData}</Text>}
        />
      </View>
    );
  }
}

五、學習中遇到的問題

1.在切換React-native項目時,一定要關閉上一個項目的react packager服務窗口,否則會出現如下錯誤:

Application xxxx has not been registered.This is either due to a require() error during initialization or failure to call AppRegistry.registerComponent.

2.相比Java,JavaScript在出現語法錯誤和bug時,更不容易定位到錯誤位置,因此在編寫JavaScript時一定要更加的細心。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容