9.组件生命周期.html 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <script src="../../babel.min.js"></script>
  9. <script src="../../react.development.js"></script>
  10. <script src="../../react-dom.development.js"></script>
  11. </head>
  12. <body>
  13. <div id="root"></div>
  14. <script type="text/babel">
  15. const root = ReactDOM.createRoot(document.querySelector('#root'));
  16. class Clock extends React.Component {
  17. constructor(props) {
  18. super(props);
  19. this.state = {
  20. now: new Date(),
  21. };
  22. }
  23. // 给组件添加生命周期 就是给组件实例添加对应钩子方法即可
  24. componentDidMount() {
  25. this.timer = setInterval(() => {
  26. // 更新状态 now
  27. // 在React中 响应式的更新状态的 唯一方式:调用组件实例的setState方法。setState方法在修改状态的时候 就是 新值 与 旧值合并后再覆盖掉旧状态
  28. this.setState({ now: new Date() });
  29. }, 1000);
  30. }
  31. componentDidUpdate() {
  32. console.log('comp updated');
  33. }
  34. componentWillUnmount() {
  35. clearInterval(this.timer);
  36. }
  37. render() {
  38. return <h3>当前时间为:{this.state.now.toLocaleString()}</h3>;
  39. }
  40. }
  41. root.render(<Clock />);
  42. </script>
  43. </body>
  44. </html>