useState
作用: 用于函数式组件操作 state,类似于类组件的 setState
写法:[state, setState] = useState(initValue)
- state:状态变量名
- setState:更新状态函数
- 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 两种写法:
- setState(newValue):参数为非函数,直接指定新状态值
- setState(value => newValue):参数为函数,接收旧状态值,返回新状态值
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
作用: 在函数组件中执行副作用操作,类似于类组件中的生命周期钩子。
useEffect(()=>{
return () = {
}
},[])
副作用操作:
可以将 useEffect Hook 看着三个生命周期函数的组合:
- componentDidMount()
- componentDidUpdate()
- componentWillUnmount()
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>;
}
useRef
作用: 在函数组件中存储或查找组件内的标签或其他数据,类似 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>;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)