每天一点点之 taro 框架 - 生命周期 & state

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

 

转载于:https://www.cnblogs.com/cap-rq/p/10900627.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值