hooks之useState

import React, {
      Component, useState } from 'react'

// 类写法
class App extends Component {
     
  constructor() {
     
    super()
    this.state = {
     
      count: 0,
    }
  }
  render() {
     
    const {
      count } = this.state
    return (
      <button onClick={
     () => {
      this.setState({
      count: count + 1 }) }}>Click ({
     count})</button>
    )
  }
}

// hooks写法
function UseStateAPI(props) {
     
  const [count, setCount] = useState(0)
 // const [sum,setSum] = useState(() =>{
     
    // 回调延迟初始化sum的值,只会运行一次
 //  return props.defaultSum || 0
 // })
  
  return (
    <button onClick={
     () => {
      setCount(count + 1) }}>Click ({
     count})</button>
  )
}

export default UseStateAPI  

从以上看出类定义state变量的区别,更简洁

你可能感兴趣的:(前端技术,hooks,react,reactjs)