React Hook入門小案例 在函數式組件中使用state響應式數據給大家演示了最簡單的 Hook操作 那么 我們繼續(xù)
首先 Hook官方介紹 他沒有破壞性是完全可選的 百分比兼容 也就說 我們一起的 類 class的方式也完全可以用
只要 react 16,8以上就可以使用
Hook本身不會影響你的react的理解 恰恰相反 官方認為 他會讓react理解更加容易
至于 Hook的修改動機在于 他認為當組件很多時 類的方式很不易理解
而且這是一種剪輯式的修改方式 比如 你的老項目 你之前的還是可以繼續(xù)用class 新的用Hook管理函數式 他們之間不會發(fā)生沖突
‘
然后 我們來說第二個 Effect Hook
’
好 那我們來開啟代碼 編寫代碼如下
import React from "react";
export default class AppRouter extends React.Component{
constructor(props){
super(props);
this.state = {
name: "小貓貓"
}
}
componentDidMount = ()=>{
document.title = this.state.name;
}
render(){
return (
<div>
Hello World
</div>
)
}
}
我們在界面寫了很普通的案例 Hello World
然后在componentDidMount 頁面掛載完畢的生命周期中執(zhí)行了 將頁面title內容改為this.state.name的指令
然后運行結果如下
沒有什么問題
我們可以在頁面內容中加這樣一個按鈕
<button onClick= { ()=>{ this.setState({ name: "大貓貓" }) } }>更改title</button>
點擊后改變name的值
我們運行代碼 會發(fā)現 點擊之后 title的值并不會隨著點擊而變化
但是其實我們心里清楚這肯定是變化了的
那么 我們就可以去寫
componentDidUpdate() {
document.title = this.state.name;
}
利用 componentDidUpdate 監(jiān)聽數據變化 當響應式數據變化重新渲染一次title的內容
這次點擊后 title的內容也就變化了
其實這樣寫多少還是有點撈的 我們可以用新特性去實現
我們將代碼改成這樣
import React,{ useState,useEffect } from "react"
const MyComponent = () => {
const [name,setName] = useState("小貓貓");
/*
useEffect相當于三個生命周期函數
分別是
componentDidMount //元素掛載完成
componentDidUpdate //響應式數據更改
componentWillUnmount //組件銷毀前
*/
useEffect(() => {
document.title = name;
})
return (
<div>
Hello World
<button onClick={ ()=> { setName("大貓貓")} }>更改title</button>
</div>
);
};
export default MyComponent;
運行項目
顯然開始渲染的沒有什么問題
然后 我們點擊按鈕
內容也是改變成功
這里正如我們注釋寫的那樣 useEffect相當于三個生命之前函數
componentDidMount //元素掛載完成
componentDidUpdate //響應式數據更改
componentWillUnmount //組件銷毀前
官方不會去動你的蛋糕
它也可以單獨去相當于某一個生命周期函數
我們將 useEffect 上面的代碼改成
useEffect(() => {
document.title = name;
// eslint-disable-next-line react-hooks/exhaustive-deps
},[]);
后面加個空數組
這樣 他就只相當于 componentDidMount
運行項目
第一次渲染上去了
然后我們點擊按鈕
就不會變化了 因為他目前只有componentDidMount的作用文章來源:http://www.zghlxwxcb.cn/news/detail-489241.html
如果你在最后面加個 return
那么 這個 return中的內容 就是組件銷毀后會執(zhí)行的componentWillUnmount邏輯函數文章來源地址http://www.zghlxwxcb.cn/news/detail-489241.html
到了這里,關于React 應用 Effect Hook 函數式中操作生命周期的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!