react 初探:类组件、状态和生命周期
2018-02-13 14:15
756 查看
react 除了提供函数式组件外,还提供了类组件,类组件提供了状态属性,下面一起吧之前的函数组件转换成类组件。
替换 render() 方法中的 this.props.date 为 this.state.date
添加类构造函数
经过修改之后的最终代码如下:
这样,当调用Clock组件时,能够实现页面上的具体时刻。但是这样做还是有些问题,无法做到每秒钟都更新组件,这里不能像上一章节,直接采用setInterval(tick, 1000);的方式来进行每秒钟更新,需要使用类组件提供的生命周期函数才可以。
当Clock组件DOM被清除时需要将计时器也销毁,需要在结束生命周期函数中将该计时器销毁。
最后,贴出整个流程的完整代码:
可以做到美妙都刷新DOM。
/* 类组件定义 */ class Clock extends React.Component{ render(){ return ( <div> <h1>Hello,World</h1> <h2>It is {this.props.date.toLocaleTimeString()}.</h2> </div> ); } }
替换 render() 方法中的 this.props.date 为 this.state.date
class Clock extends React.Component { render() { return ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } }
添加类构造函数
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> ); } }
经过修改之后的最终代码如下:
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')
);
这样,当调用Clock组件时,能够实现页面上的具体时刻。但是这样做还是有些问题,无法做到每秒钟都更新组件,这里不能像上一章节,直接采用setInterval(tick, 1000);的方式来进行每秒钟更新,需要使用类组件提供的生命周期函数才可以。
类的生命周期
componentDidMount() 钩子在组件输出被渲染到 DOM 之后运行。我们将计时器的设置放在生命周期函数内。componentDidMount() { this.timerID = setInterval( () => this.tick(), 1000 ); }
当Clock组件DOM被清除时需要将计时器也销毁,需要在结束生命周期函数中将该计时器销毁。
componentWillUnmount() { clearInterval(this.timerID); }
最后,贴出整个流程的完整代码:
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 ( <div> <h1>Hello, world!</h1> <h2>It is {this.state.date.toLocaleTimeString()}.</h2> </div> ); } } ReactDOM.render( <Clock />, document.getElementById('root') );
可以做到美妙都刷新DOM。
相关文章推荐
- 【ReactJS】通过一个例子学习React组件的生命周期
- React 组件的生命周期总结
- React Native(RN)-组件生命周期
- react组件的生命周期
- React Native 中组件的生命周期
- React组件的生命周期及执行顺序
- React Native 学习-组件说明和生命周期
- React 组件生命周期
- React第三方组件4(状态管理之Reflux的使用③TodoList中)
- react系列(6)组件生命周期钩子函数
- javaweb-react的入门遇到的问题二:组件的生命周期
- React第三方组件6(状态管理之Mobx的使用③TodoList中)
- React组件生命周期详解
- React.js 基础入门三 ---组件状态state
- React组件生命周期
- react-native组件的生命周期
- React 组件生命周期
- React Native 中组件的生命周期
- React-Native子组件修改父组件的几种方式,兄弟组件状态修改
- [转] 深入理解React 组件状态(State)