Hooks
函数式组件中使用一些class组件中才有的特性
1.useState
const[变量名,更改变量的函数名(内置函数)] = useState(初始值)
useState()
参数:第一次初始化指定的值在内部作缓存
返回值:包含两个元素的数组,第一个内部当前状态值(变量名来接受的值),第二个为更新状态的函数
import React,{Component,useState} from "react";
//函数组件写法
// class Hooks extends Component{
// state ={count:0}
// add = ()=>{
// this.setState({
// count:this.state.count+1
// })
// }
// render(h) {
// return(
// <div>
// <div>数量:{this.state.count}</div>
// <button onClick={this.add}>点击我</button>
// </div>
// )
// }
// }
const Hooks = ()=>{
//const[变量名,更改变量的函数名(内置函数)] = useState(初始值)
//useState()
//参数:第一次初始化指定的值在内部作缓存
//返回值:包含两个元素的数组,第一个内部当前状态值(变量名来接受的值),第二个为更新状态的函数
const [count,setCount] = useState(0)
const add=()=>{
//1.直接传值
// setCount(count+1)
//2.传一个函数
setCount(count=>count+1)
}
return(
<div>
<div>数量:{count}</div>
<button onClick={add}>点击我</button>
</div>
)
}
export default Hooks
2.useEffect
模拟生命周期函数, componentDidMount
和 componentWillUnmount
以及componentDidUpdate
useEffect(想要执行的操作,[监听指定内容])
【注】监听内容为空不监听,则调用一次;不维护则监听所有,有改变就会调取
import React, { Component, useState, useEffect } from "react";
import ReactDOM from 'react-dom'
// class Hooks extends Component{
// state ={count:0}
// componentDidMount(){
// this.timer = setInterval(()=>{
// this.setState(state=>({count:state.count+1}))
// },1000)
// }
// componentWillUnmount(){
// clearInterval(this.timer)
// }
// unmount(){
// ReactDOM.unmountComponentAtNode(document.getElementById("root"))
// }
// render(h) {
// return(
// <div>
// <div>数量:{this.state.count}</div>
// <button onClick={this.unmount}>卸载组件</button>
// </div>
// )
// }
// }
const Hooks = () => {
const [count, setCount] = useState(0)
//useEffect(想要执行的操作,[监听指定内容])
//【注】监听内容为空不监听,则调用一次;不维护则监听所有,有改变就会调取
useEffect(() => {
//加载完成或更新就会执行
let timer = setInterval(() => {
setCount(count => count + 1)
}, 1000)
//return返回的函数在组件卸载前执行
return ()=>{
clearInterval(timer)
}
}, [])
const unmount = ()=>{
ReactDOM.unmountComponentAtNode(document.getElementById("root"))
}
return (
<div>
<div>数量:{count}</div>
<button onClick={unmount}>卸载组件</button>
</div>
)
}
export default Hooks
3.useRef
import React, { Component, createRef, useState, useRef } from "react";
// class Hooks extends Component{
// state ={count:0}
// myRef = React.createRef()
// add = ()=>{
// this.setState({
// count:this.state.count+1
// })
// }
// show = ()=>{
// alert(this.myRef.current.innerText)
// }
// render(h) {
// return(
// <div>
// <div ref={this.myRef}>数量:{this.state.count}</div>
// <button onClick={this.add}>点击我</button>
// <button onClick={this.show}>展示count</button>
// </div>
// )
// }
// }
const Hooks = ()=>{
const [count,setCount] = useState(0)
const myRef = useRef()
const add=()=>{
setCount(()=>count+1)
}
const show = ()=>{
alert(myRef.current.innerText)
}
return(
<div>
<div ref={myRef}>数量:{count}</div>
<button onClick={add}>点击我</button>
<button onClick={show}>展示count</button>
</div>
)
}
export default Hooks