react学习笔记4--状态和生命周期

学习使用clock组件使代码可复用,从封装时钟开始:

function Clock(props) {
    return(
        <div>
            <h1>hello,world</h1>
            <h2>it is {props.date.toLocaleTimeString()}</h2>
        </div>
    );
}

function tick() {
    ReactDOM.render(
        <Clock date={new Date()} />,
        document.getElementById('root')
    );
}

setInterval(tick,1000);

实际上clock应该自己实现定时和更新

用类定义的组件有一些额外的特性,指的就是局部状态

class Clock extends React.Component {
    constructor(props) {//类构造函数
        super(props);
        this.state = {date:new Date()};
    }
    render() {//访问类组件的局部状态
        return(
            <div>
                <h1>hello,world</h1>
                <h2>it is {this.state.date.toLocaleTimeString()}</h2>
            </div>
        );
    }
}

ReactDOM.render(
    <Clock />,
    document.getElementById('root')
);

在类中添加生命周期方法

class Clock extends React.Component {
    constructor(props) {//类构造函数
        super(props);
        this.state = {date:new Date()};
    }

    ComponentDidMount() {//设置定时器timerID
        this.timerID = setInterval(
            () => this.tick(),
            1000
        );

    }

    ComponentWillUnmount(){//取消定时器timerID
        clearInterval(this.timerID);

    }

    tick() {
        this.setState({
            date:new Date()
        });
    }

    render() {//访问类组件的局部状态
        return(
            <div>
                <h1>hello,world</h1>
                <h2>it is {this.state.date.toLocaleTimeString()}</h2>
            </div>
        );
    }
}

ReactDOM.render(
    <Clock />,
    document.getElementById('root')
);

正确使用State状态

setState()

  1. 不要直接修改state
this.state.comment = 'hello';//错误
this.setState({comment:'hello'});//正确

唯一可以分配this.state的地方是构造函数

  1. state更新可能是异步的

将多个setState()调用合并为一次更新,接收一个函数,接收前一个状态值作为第一个参数,将更新后的值作为第二个参数

this.setState({
    counter:this.state.counter+this.props.increment,
});//错误

this.setState(() => ({
    counter:preState.counter+props.increment
}));//正确
this.setState(function(prevState,props) {
    return{
        counter:prevState.counter+props.increment
    };
});

state状态更新会被合并

状态值可以单独更新

constructor(props){
    super(props);
    this.state = {
      posts:[],
      comments:[]
    };
}

componentDidMount(){
    fetchPosts().then(response =>{
        this.setState({
            posts:response.posts
        });
    });
    fetchComments().then(response => {
        this.setState({
            comments:response.comments
        });
    });
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值