React Hooks 是 React 16.7.0-alpha
版本推出的新特性, 有了React Hooks,在 react 函数组件中,也可以使用类组件(classes components)的 state 和 组件生命周期。
useState Hooks
import React,{ useState } from 'react'
const Hooks = () => {
const [ count,setCount ] = useState( 0 )
return (
<div>
hooks
<hr/>
<button onClick = { () => setCount( count + 1 ) }>修改count</button>
<p> { count } </p>
</div>
)
}
export default Hooks
useEffect Hook
import React,{ useState,useEffect } from 'react'
const Hooks = () => {
const [ count,setCount ] = useState( 0 )
useEffect (() => {
console.log( 'state发生了改变' )
document.title = `你点击了${ count }次`
})
return (
<div>
hooks
<hr/>
<button onClick = { () => setCount(count + 1) }>修改count</button>
<p> { count } </p>
</div>
)
}
export default Hooks