State与组件生命周期

State

顾名思义,state用于表示组件的状态。相当于组件的私有变量,只可以在组件内部修改,完全受控于当前组件。
是由类定义的组件所特有的。

状态的声明

class Clock extends React.Component{
    constructor(props){
        super(props);
        this.state = {date:new Date()};//对state进行初始化
    }
    render(){//类组件唯一必须的方法
        return (<div>
            <p>hello world</p>
            <h2>{this.state.date.toLocaleTimeString()}</h2>
        </div>);
    }
}

如果想要实现实时更新的时钟,那就需要与生命周期的钩子函数结合。

生命周期:

1.初始化

constructor()

2.挂载

static getDerivedStateFromProps()
组件实例化后和属性更新后
render()
componentDidMount()
组件挂载后立即调用

3.更新

static getDerivedStateFromProps()
shouldComponentUpdate()
接收到新属性和状态时,渲染前调用,返回布尔值,决定是否更新
render()
getSnapshotBeforeUpdate()
渲染提交给DOM之前调用,返回值传给componentDidUpdate(),可以返回null
componentDidUpdate()

4.卸载

componentWillUnmount()

5.错误处理

componentDidCatch()

在挂载后新建一个定时器,在卸载时清除定时器,利用this.setState()就可以实现实时时钟。

class Clock extends React.Component{
    constructor(props){
        super(props);
        this.state = {date:new Date()};//对state进行初始化
    }
    tick(){
        this.setState({date:new Date()})
    }
    //挂载
    componentDidMount() {
        console.log('4-componentDidMount');
        this.timerID = setInterval(
             () => this.tick(),
        1000);
    }
    
    //卸载
    componentWillUnmount(){
        clearInterval(this.timerID);
    }
    render(){//类组件唯一必须的方法
        return (<div>
            <p>hello world</p>
            <h2>{this.state.date.toLocaleTimeString()}</h2>
        </div>);
    }
}
ReactDOM.render(<Clock />,document.getElementById('root'));

用this.setState({})来更新state,constructor()中初始化state

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值