作用: 用于函数式组件操作 state,类似于类组件的 setState
写法:[state, setState] = useState(initValue)
类组件的 setState
import React, { Component } from 'react'
export default class BaseRender extends Component {
state = {count:0}
add = ()=>{
this.setState(state=>({count: this.state.count+1}))
}
render() {
return (
<div>
<h2>{this.state.count}</h2>
<button onClick={this.add}>Click + 1</button>
</div>
)
}
}
setState 两种写法:
import React, {useState} from "react";
export default function BaseRender() {
const [count, setCount] = useState(0);
function add() {
setCount(count+1)
}
return <div id="mid">
<h3>{count}</h3>
<button onClick={add}>Click</button>
</div>;
}
作用: 在函数组件中执行副作用操作,类似于类组件中的生命周期钩子。
useEffect(()=>{
// 执行任何副作用操作
return () = {
// 组件卸载前执行
// 可以做收尾工作比较清除定时器,取消订阅
}
},[]) // 如果指定第二个函数,回调函数只会在第一次 render() 后执行,相当于 componentDidMount
副作用操作:
可以将 useEffect Hook 看着三个生命周期函数的组合:
import React, {useEffect, useState, useRef} from "react";
import ReactDOM from "react-dom";
export default function BaseRender() {
const [count, setCount] = useState(0);
function add() {
setCount(count=>count+1)
}
useEffect(()=>{
let timer = setInterval(()=>{
setCount(count+1)
},1000)
return ()=>{
clearInterval(timer)
}
},[count])
function unmount(){
ReactDOM.unmountComponentAtNode(document.getElementById('mid'))
}
return <div id="mid">
<h3>{count}</h3>
<button onClick={add}>Click</button>
<button onClick={unmount}>unmount root</button>
</div>;
}
作用: 在函数组件中存储或查找组件内的标签或其他数据,类似 React.createRef()
const refContainer = useRef()
import React, {useRef} from "react";
import ReactDOM from "react-dom";
export default function BaseRender() {
const myRef = useRef()
function show(){
console.log(111)
alert(myRef.current.value)
}
return <div id="mid">
<input type="text" ref={myRef}/>
<button onClick={show}>Click show ref</button>
</div>;
}