[REACT] Examples of the use of a clock hook react class rewritable

React Chinese network has written a class on the clock example https://react.docschina.org/docs/state-and-lifecycle.html ,

React now launched a new hook api, they use hook easily rewritten at this example:

import React, { useState, useEffect} from 'react';
import ReactDOM from 'react-dom';


function Clock(){
  const [date,setDate]=useState(new Date());

  useEffect(()=>{
    function tick(){
      setDate(new Date());
    }
    const timerID = setInterval(tick,1000);

    return function clearTick(){
      clearInterval(timerID);
    };
  });
  
  return(
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {date.toLocaleTimeString()}.</h2>
    </div>
  );  
}

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

 

Guess you like

Origin www.cnblogs.com/sx00xs/p/11756421.html