react-native组件生命周期

本文详细总结了React Native组件的生命周期,包括this.setState的用法、生命周期的三个阶段(实例化、存在、销毁)以及各阶段的重要方法,如getInitialState、componentWillMount、componentDidMount等,并探讨了在不同阶段中何时使用this.setState及其注意事项。
摘要由CSDN通过智能技术生成

react-native的组件生命周期总结:

 

生命周期 调用次数 能否使用setState()
getDefaultProps 1(全局调用一次)
getInitialState 1
componentWillMount 1
render >=1
componentDidMount 1
componentWillReceiveProps >=0
shouldComponentUpdate >=0
componentWillUpdate >=0
componentDidUpdate >=0
componentWillUnmount 1

注意:当调用this.setState时就会调用组件的render方法,但React框架会根据dom节点状态确定是否需要重新渲染

this.setState

this.setState用法

        this.setState(arg1,arg2),arg1可以是对象也可以是函数(必需),arg2是一个回调函数,在此函数中可以获取被setState更改后的state值,arg2可为空。

当arg1是对象时的写法:

this.setState({
    key : val
},()=>{
    console.log(this.state.key);
})
​

当arg1是函数时的写法:

//第一种写法(在更改state值之前执行一些操作)
this.setState(
    (prevState,props)=>{
        console.log(prevState);
        return { key : prevState.key+props.val };
},()=>{
    console.log(this.state.key);
}
);

​//第二种写法
this.setState(
    (prevState,props)=>({
        key : prevState.key+props.val
}),()=>{
    console.log(this.state.key);
}
);

this.setState的使用场景

        当通过this.state.key = val直接修改state值时,虽然可以更改state值,但是不会触发re-render对组件进行重新渲染,使用this.setState()更改state数据值,会触发re-ren

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值