learning/3.state/index.js

43 lines
852 B
JavaScript

// // 不推荐的方式
// function tick() {
// const e = <h1>现在时间是{new Date().toLocaleTimeString()}</h1>;
// ReactDOM.render(
// e,
// document.getElementById('root')
// );
// }
// setInterval(tick, 1000);
// 通过state 添加自定属性 触发刷新
class Clock extends React.Component {
constructor(props){
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerId = setInterval(()=> this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return <h1>现在时间, {this.state.date.toLocaleTimeString()}</h1>;
};
}
ReactDOM.render(
<Clock/>,
document.getElementById('root')
);