React 更新 state

index.js

import React from 'react'
import ReactDOM from 'react-dom'

class Clock extends React.Component {
  constructor() {
    super()
    this.state = {
      time: 'time',
      timer: null,
    }
  }

  componentDidMount() {
    this.tick()
  }
  componentWillUnmount() {
    clearInterval(this.state.timer)
  }

  tick() {
    const timer = setInterval(() => {
      this.setState({ time: new Date().toLocaleTimeString() })
    }, 1000)
    this.setState({ timer })
  }

  render() {
    return <h1>{this.state.time}</h1>
  }
}

ReactDOM.render(<Clock />, document.getElementById('root'))
原文地址:https://www.cnblogs.com/aisowe/p/15250023.html