注意:从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方法是异步的

