React State(状态)简单演示

前端之家收集整理的这篇文章主要介绍了React State(状态)简单演示前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

添加一个类构造函数来初始化状态 this.state,类组件应始终使用 props 调用基础构造函数

  1. import React,{ Component } from 'react';
  2. import ReactDOM from 'react-dom';
  3. import './index.css';
  4. import App from './App';
  5. import * as serviceWorker from './serviceWorker';
  6. class Clock extends React.Component{
  7. constructor(props){
  8. super(props);
  9. this.state={
  10. time:new Date()
  11. }
  12. }
  13. render(){
  14. return(
  15. <div>{this.state.time.toLocaleTimeString()}</div>
  16. )
  17. }
  18. }
  19. ReactDOM.render(
  20. <div>
  21. <Clock/>
  22. </div>,document.getElementById('example')
  23. );
  24. serviceWorker.unregister();

 

 

将生命周期方法添加到类中
每当 Clock 组件第一次加载到 DOM 中的时候,我们都想生成定时器,这在 React 中被称为挂载。
同样,每当 Clock 生成的这个 DOM 被移除的时候,我们也会想要清除定时器,这在 React 中被称为卸载。

componentDidMount() 与 componentWillUnmount() 方法被称作生命周期钩子。
在组件输出到 DOM 后会执行 componentDidMount() 钩子,我们就可以在这个钩子上设置一个定时器。
this.timerID 为定时器的 ID,我们可以在 componentWillUnmount() 钩子中卸载定时器。

  1. import React,1)"> Date()
  2. }
  3. }
  4.  
  5. //当 Clock 的输出插入到 DOM 中时
  6. componentDidMount(){
  7. this.timer=setInterval(()=>{
  8. this.tick()
  9. },1000);
  10. }
  11. Clock 组件被从 DOM 中移除
  12. componentWillUnmount(){
  13. clearInterval(.timer)
  14. }
  15. tick(){
  16. .setState({
  17. time: Date()
  18. })
  19. }
  20. render(){
  21. )
  22. );
  23. serviceWorker.unregister();

 

数据自顶向下流动/单向数据流

  1. import React,1)">;
  2.  
  3. function DateFormat(props){
  4. (
  5. props.date.toLocaleTimeString()
  6. )
  7. }
  8. class Clock extends React.Component{
  9. constructor(props){
  10. super(props);
  11. (
  12. <DateFormat date={this.state.time}/>
  13. )
  14. );
  15. serviceWorker.unregister();

 

为了表明所有组件都是真正隔离的,我们可以创建一个 App 组件,它渲染三个Clock

 

 

 

猜你在找的React相关文章