在hooks裡面useEffect其實就是生命週期,也就是放在裡面的程式,再載入畫面時也會被跟著執行。
就類似於JQ的
$(document).ready(function(){
});
比較不同的是,每個hook有改變的時候useEffect就會在執行一次,不像JQ只執行第一次。
import React, { useState , useEffect} from 'react'
import './app4.scss';
export default function App3() {
const [goitem, goItem] = useState(['react']);
const additem = () =>{
goItem('good')
}
useEffect(() => {
document.title = `${goitem}`
})
return (
<div className="div_bg">
<button onClick={additem}>點我</button>
</div>
)
}
import React, { useState , useEffect} from 'react'
import './app4.scss';
export default function App3() {
const [goitem, goItem] = useState(['react']);
const additem = () =>{
goItem('good')
}
const additem2 = () =>{
goItem('react-yes')
}
useEffect(() => {
additem2()
document.title = `${goitem}`
})
return (
<div className="div_bg">
<button onClick={additem}>點我</button>
</div>
)
}
會發現被綁死,因為只要有更新狀態就會在執行一次additem2(),所以就被綁死了
import React, { useState , useEffect} from 'react'
import './app4.scss';
export default function App3() {
const [goitem, goItem] = useState(['react']);
const [gotext, goText] = useState(['']);
const additem = () =>{
goItem('good')
}
useEffect(() => {
console.log('123456789')
document.title = `${goitem}`
})
return (
<div className="div_bg">
<input type='text' onChange={(e)=> goText(e.target.value)} value={gotext}/>
<button onClick={additem}>點我</button>
</div>
)
}
會發現 input 每輸入一個字就會觸發一次console.log
import React, { useState , useEffect} from 'react'
import './app4.scss';
export default function App3() {
const [goitem, goItem] = useState(['react']);
const [gotext, goText] = useState(['']);
const additem = () =>{
goItem('good')
}
useEffect(() => {
console.log('123456789')
document.title = `${goitem}`
},[goitem])
return (
<div className="div_bg">
<input type='text' onChange={(e)=> goText(e.target.value)} value={gotext}/>
<button onClick={additem}>點我</button>
</div>
)
}
設定goitem為觸發的指令,只要有更新goitem就會啟動生命週期,這樣就能指定事件來打API