前言
Hooks出來已經有段時間了趴俘,相信大家都用過段時間了线衫,有沒有小伙伴們遇到坑呢步鉴,我這邊就有個setInterval
的坑孩等,和小伙伴們分享下解決方案。
問題
寫個count
每秒自增的定時器署海,如下寫法結果吗购,界面上count
為1
?
function Counter() {
let [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-error-w4qu6
如果某些特定值在兩次重渲染之間沒有發(fā)生變化砸狞,你可以通知
React
跳過對effect
的調用捻勉。就是將第二個參數改成[]
,類似于更接近類組件的componentDidMount
和componentWillUnmount
生命周期,只執(zhí)行一次刀森。effect
的第二個參數中傳入的值就是 它更改的話踱启,effect
也會重新執(zhí)行一遍的值。
因為Effect
的第二個參數為[]
,沒有依賴,Effect
只會執(zhí)行一次禽捆。setInterval
中拿到的是第一次渲染時的閉包count
笙什,所以count
永遠是0
,界面會一直顯示1
,如下所示:
function Counter() {
let [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(0 + 1);
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
那有些小伙伴會說,如果我們直接往第二個參數加count
呢
function Counter() {
//...
useEffect(() => {
const id = setInterval(() => {
setCount(count + 1);
}, 1000);
return () => clearInterval(id);
}, [count]);
//...
}
這樣效果是對的胚想,但是性能不好琐凭。每當count
更改了,useEffect
就會渲染一次,定時器也會不停的被新增與移除浊服。如下所示:
//第一次
function Counter() {
//...
useEffect(() => {
const id = setInterval(() => {
setCount(0 + 1);
}, 1000);
return () => clearInterval(id);
}, [0]);
//...
}
//第二次
function Counter() {
//...
useEffect(() => {
const id = setInterval(() => {
setCount(1 + 1);
}, 1000);
return () => clearInterval(id);
}, [1]);
//...
//第N次
}
那到底要怎么做才能有保障性能统屈,定時器只監(jiān)聽一次,又使定時器起作用呢牙躺?
方案一愁憔、函數式更新
useState
中的set方法可接收函數,該函數將接收先前的state
孽拷,并返回一個更新后的值吨掌。這樣定時器每次拿到的是最新的值。
function Counter() {
let [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => {
setCount(v => {
return v + 1;
});
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-usestate-grres
方案二脓恕、用useRef
useRef
返回一個可變的ref
對象,返回的ref
對象在組件的整個生命周期內保持不變膜宋。
將定時器函數提取出來,每次定時器觸發(fā)時炼幔,都能取到最新到count
.
function Counter() {
let [count, setCount] = useState(0);
const myRef = useRef(null);
myRef.current = () => {
setCount(count + 1);
};
useEffect(() => {
const id = setInterval(() => {
myRef.current();
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-useref-cgif3
思考:為什么不直接
setInterval(myRef.current, 1000)
這樣寫不行呢,還要包個方法返回秋茫?
function Counter() {
let [count, setCount] = useState(0);
const myRef = useRef(null);
myRef.current = () => {
setCount(count + 1);
};
useEffect(() => {
const id = setInterval(myRef.current, 1000);
return () => clearInterval(id);
}, []);
return <h1>{count}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-useref-error-52dm0
下面的例子可以很好的解釋。假如把myRef.current
為cur
變量,定時器的第一個參數為interval
變量乃秀,cur
變量更改肛著,interval
的取的還是之前賦值的值。
var cur=()=>{var count=0;console.log(count)};
var interval=cur;
var cur=()=>{var count=1;console.log(count)};
interval();//0
var cur=()=>{var count=0;console.log(count)};
var interval=()=>{cur()};
var cur=()=>{var count=1;console.log(count)};
interval();//1
方案三跺讯、自定義hook
可以寫個自定義hook
枢贿,方便重復使用。
function useInterval(fun) {
const myRef = useRef(null);
useEffect(() => {
myRef.current = fun;
}, [fun]);
useEffect(() => {
const id = setInterval(() => {
myRef.current();
}, 1000);
return () => clearInterval(id);
}, []);
}
function Counter() {
let [count, setCount] = useState(0);
useInterval(() => {
setCount(count + 1);
});
return <h1>{count}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-ownhooks-0tpxe
方案四抬吟、用useReducer
將count
變量存入reducer
中萨咕,使用useReducer
更新count
function reducer(state, action) {
switch (action.type) {
case "increment":
return state + 1;
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, 0);
useEffect(() => {
const id = setInterval(() => {
dispatch({ type: "increment" });
}, 1000);
return () => clearInterval(id);
}, []);
return <h1>{state}</h1>;
}
https://codesandbox.io/embed/hooks-setinterval-usereducer-2byrm
還有什么好的方案歡迎小伙伴們留言評論~~
Happy coding .. :)
相關鏈接
https://raoenhui.github.io/react/2019/11/07/hooksSetinterval/index.html
https://zh-hans.reactjs.org/docs/hooks-effect.html
https://zh-hans.reactjs.org/docs/hooks-reference.html
https://overreacted.io/making-setinterval-declarative-with-react-hooks/