1、setState
setState更新數(shù)據(jù)是異步的,如果想獲取更新完的數(shù)據(jù),需要通過(guò)第二個(gè)參數(shù)回調(diào)函數(shù)來(lái)獲取
//對(duì)象式setState
add = ()=>{
const {count} = this.state
this.setState({count: count + 1}, ()=>{
console.log(this.state.count)
})
}
//函數(shù)式setState()
add = ()=>{
const {count} = this.state
this.setState((state,props)=>{
console.log(state,props)
return {count:state.count+1}
})
}
2、lazyLoad,用的時(shí)候再調(diào)用,不會(huì)預(yù)先調(diào)用,需要用suspence包裹注冊(cè)路由
import React, { Component,lazy,Suspense} from 'react'
import {NavLink,Route} from 'react-router-dom'
// import Home from './Home'
// import About from './About'
import Loading from './Loading'
const Home = lazy(()=> import('./Home') )
const About = lazy(()=> import('./About'))
<Suspense fallback={<Loading/>}>
{/* 注冊(cè)路由 */}
<Route path="/about" component={About}/>
<Route path="/home" component={Home}/>
</Suspense>
3、stateHook
userState
函數(shù)組件中使用state,通過(guò)調(diào)用React.useState()使用,該數(shù)組兩個(gè)變量,第一個(gè)存儲(chǔ)狀態(tài)值,第二個(gè)存儲(chǔ)改變狀態(tài)的方法,通過(guò)解構(gòu)賦值取出來(lái)即可
//設(shè)置state初始值,并獲取調(diào)用函數(shù)
const [count,setCount] = React.useState(0)
function add(){
//setCount(count+1) //第一種寫(xiě)法
setCount(count => count+1 )
}
userEffect,監(jiān)聽(tīng)函數(shù)
React.userEffect(,[])第二個(gè)參數(shù)是檢測(cè)對(duì)象,如果監(jiān)測(cè)空數(shù)組,則相當(dāng)于類式組件中的componentDidMount,只在加載的時(shí)候調(diào)用,其可以檢測(cè)數(shù)值的變化,所以也可以當(dāng)componentDidUpdate使用
userEffect的第一個(gè)參數(shù)可以寫(xiě)一個(gè)返回函數(shù),其返回函數(shù)相當(dāng)于componentWillUnmount
React.useEffect(()=>{
let timer = setInterval(()=>{
setCount(count => count+1 )
},1000)
return ()=>{
clearInterval(timer)
}
},[])
可以把 useEffect Hook 看做如下三個(gè)函數(shù)的組合
? ? ? ? componentDidMount()
? ? ? ? componentDidUpdate()
? ? ?? ?componentWillUnmount()?
RefHook
(1). Ref Hook可以在函數(shù)組件中存儲(chǔ)/查找組件內(nèi)的標(biāo)簽或任意其它數(shù)據(jù)
(2). 語(yǔ)法: const refContainer = useRef()
(3). 作用:保存標(biāo)簽對(duì)象,功能與React.createRef()一樣
const myRef = React.useRef()
//提示輸入的回調(diào)
function show(){
alert(myRef.current.value)
}
<input type="text" ref={myRef}/>
<button onClick={show}>點(diǎn)我提示數(shù)據(jù)</button>
Fragment
<Fragment>可以取代無(wú)效的<div>標(biāo)簽,編譯的時(shí)候會(huì)自動(dòng)丟失忽略,不再渲染真實(shí)DOM
Context,組件間通信方式,常用于祖組件 和 后代組件間的通信
//1、創(chuàng)建Context對(duì)象
const MyContext = React.createContext()
const {Provider,Consumer} = MyContext
//傳遞
<Provider value={{username,age}}>
<B/>
</Provider>
//類式組件聲明接收context
static contextType = MyContext
const {username,age} = this.context
//函數(shù)式組件與類式組件都可以接受的方式
<Consumer>
{value => `${value.username},年齡是${value.age}`}
</Consumer>
PureComponent
Component的2個(gè)問(wèn)題?
> 1. 只要執(zhí)行setState(),即使不改變狀態(tài)數(shù)據(jù), 組件也會(huì)重新render() ==> 效率低
>
> 2. 只當(dāng)前組件重新render(), 就會(huì)自動(dòng)重新render子組件,縱使子組件沒(méi)有用到父組件的任何數(shù)據(jù) ==> 效率低
### 效率高的做法
> ?只有當(dāng)組件的state或props數(shù)據(jù)發(fā)生改變時(shí)才重新render()
### 原因
> ?Component中的shouldComponentUpdate()總是返回true
改進(jìn)措施:
使用PureComponent取代Component,但是push等操作的時(shí)候會(huì)出現(xiàn)問(wèn)題,不建議使用
?? ??? ?注意:?
?? ??? ??? ?只是進(jìn)行state和props數(shù)據(jù)的淺比較, 如果只是數(shù)據(jù)對(duì)象內(nèi)部數(shù)據(jù)變了, 返回false ?
?? ??? ??? ?不要直接修改state數(shù)據(jù), 而是要產(chǎn)生新數(shù)據(jù)
renderProps插槽技術(shù)
export default class Parent extends Component {
render() {
return (
<div className="parent">
<h3>我是Parent組件</h3>
<A render={(name)=><B name={name}/>}/>
</div>
)
}
}
class A extends Component {
state = {name:'tom'}
render() {
console.log(this.props);
const {name} = this.state
return (
<div className="a">
<h3>我是A組件</h3>
{this.props.render(name)}
</div>
)
}
}
ErrorBoundary
只適用于生產(chǎn)環(huán)境,測(cè)試環(huán)境還是會(huì)報(bào)錯(cuò) getDerivedStateFromError
#### 理解:
錯(cuò)誤邊界(Error boundary):用來(lái)捕獲后代組件錯(cuò)誤,渲染出備用頁(yè)面
#### 特點(diǎn):
只能捕獲后代組件生命周期產(chǎn)生的錯(cuò)誤,不能捕獲自己組件產(chǎn)生的錯(cuò)誤和其他組件在合成事件、定時(shí)器中產(chǎn)生的錯(cuò)誤
##### 使用方式:
getDerivedStateFromError(捕獲后代組件生命周期產(chǎn)生的錯(cuò)誤)配合componentDidCatch(捕獲頁(yè)面報(bào)錯(cuò))文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-475948.html
import React, { Component } from 'react'
import Child from './Child'
export default class Parent extends Component {
state = {
hasError:'' //用于標(biāo)識(shí)子組件是否產(chǎn)生錯(cuò)誤
}
//當(dāng)Parent的子組件出現(xiàn)報(bào)錯(cuò)時(shí)候,會(huì)觸發(fā)getDerivedStateFromError調(diào)用,并攜帶錯(cuò)誤信息
static getDerivedStateFromError(error){
console.log('@@@',error);
return {hasError:error}
}
componentDidCatch(){
console.log('此處統(tǒng)計(jì)錯(cuò)誤,反饋給服務(wù)器,用于通知編碼人員進(jìn)行bug的解決');
}
render() {
return (
<div>
<h2>我是Parent組件</h2>
{this.state.hasError ? <h2>當(dāng)前網(wǎng)絡(luò)不穩(wěn)定,稍后再試</h2> : <Child/>}
</div>
)
}
}
componentDidCatch()
?方法只適用于 class 組件,函數(shù)組件可以使用 ErrorBoundary 來(lái)實(shí)現(xiàn)相似的功能。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-475948.html
到了這里,關(guān)于React學(xué)習(xí)8 hooks的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!