注意:從vue過來的小朋友要注意,taro直接賦值時不會更新組件的,同react一致更新數據必須調用setState方法,例如:this.setState({name:'張三'})
1.render函數
return中的標簽可以是但標簽,也可以是多標簽
2.index.js文件內容介紹
import Taro, { Component } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
export default class Index extends Component {
config = {
navigationBarTitleText: '首頁'
}
componentWillMount () {
console.log('componentWillMount,第一次渲染之前執行,只執行一次')
}
componentDidMount () {
console.log('componentDidMount,第一次渲染之后執行,只執行一次')
}
componentWillUnmount () {
console.log('componentWillUnmount,卸載時執行')
}
componentWillUpdate () {
console.log('componentWillUpdate,state數據將要更新')
}
componentDidUpdate () {
console.log('componentDidUpdate,state數據更新過后')
}
shouldComponentUpdate (nextProps,nextState) {
// 檢查此次setState是否要進行render調用,返回true調用,false不調用
// 一般用來多次的setState調用時,提升render性能
// 判斷狀態
if(nextState.state.text == '李四')
return true;
}
componentWillReceiveProps(nextProps){
// 會在父組件傳遞給子組件的參數發生改變時觸發
}
// componentDidShow與componentDidHide在reactjs不存在,是taro為了兼容小程序實現的
componentDidShow () {
console.log('componentDidShow,顯示時觸發')
}
componentDidHide () {
console.log('componentDidHide,隱藏時觸發')
}
state = {
name:'Helloworld'
}
getName () {
return 111;
}
render () {
console.log('render,第一次運行')
return (
<View className='index'>
<View>獲取動態變量:{this.state.name}</View>
<View>獲取動態方法:{this.getName()}</View>
</View>
)
}
}
3.tarojs的生命周期
tarojs有六個生命周期
componentWillMount 第一次渲染之前執行,只執行一次
render 渲染頁面
componentDidMount 第一次渲染之后執行,只執行一次
componentWillUnmount 卸載時執行
componentWillUpdate state數據將要更新
componentDidUpdate state數據更新過后
一下兩個在reactjs不存在,是taro為了兼容小程序實現的
componentDidShow 顯示時觸發
componentDidHide 隱藏時觸發
運行截圖如下:

4.setState更新異步問題
setState方法有兩個參數, 第一個時對象,第二個時回調函數
componentDidMount () { console.log('componentDidMount,第一次渲染之后執行,只執行一次') this.setState({name:'王五'},()=>{ console.log(this.state.name,'回調') }) console.log(this.state.name,'同步') }
由運行結果可以看出,setState方法是異步的

