React to automatically create a new component with time

componentDidMount statement periodic function represents the component rendering is complete
componentWillUnmount statement periodic function components that will be uninstalled normally used (in order to prevent memory leaks Clear Timer)
11 ==> create components Clock.js component name in uppercase


12 == "error Attempted import error: './components/Clock' ' Clock' is not exported from 
the test import error:" clock "is not from." / Components / Clock "Export
Solution: state your import statements wrong again


13 ==> use components to achieve automatic time with a new
 Clock.js follows


import React,{Component} from "react";
Export default class the extends the Component Clock {
     // State fixed state name 
    State = {
        data: new Date()
    }
    
    // componentDidMount periodic function declaration completion of rendering a rear assembly 
    componentDidMount () {
         the this .timer the setInterval = (() => {
             the this .setState ({ //   this.setState fixed values for the state change data in the 
                 data: new new a Date ()
           })  
        }, 1000);
    }

    // In order to prevent memory leaks Clear timers 
    componentWillUnmount () {
        clearInterval(this.timer);
    }


    // definition of components into a specific time toLocaleTimeString 
    the render () {
         return (
             <div> 
                { the this .state.data.toLocaleTimeString ()}
             </ div>
         )
    }
}



Using Components
import Clock from "./components/Clock"
  {/* 动态组件 */}
  <Clock></Clock>

 

Guess you like

Origin www.cnblogs.com/IwishIcould/p/11966760.html