-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
记录使用Hooks遇到的问题 #19
Comments
函数每次执行都更新 current 确实没问题,但是从更加精确的控制角度来讲,是不是这样会更好: useEffect(() => {
stateRef.current = state;
}, [state]); let val = 0; 在函数组建作用域外使用可变变量,会导致该组件同时只能使用一个。 |
@liyuanqiu 嗯,像你这样比对更新的确会更好。
这个是什么意思? |
A let sum = 0;
function Button({
name,
}) {
function handleClick() {
sum += 1;
console.log(`Button(${name}) has been clicked for ${sum} times!`);
}
return (
<button
onClick={handleClick}
>
click me!
</button>
);
} In your app: function App() {
return (
<Button name="button-1" />
<Button name="button-2" />
);
} See: |
第一个例子 第二个例子你使用了useRef() setCount(countRef.current + 1); 你大可不必用函数的方式,因为这种是间接拿到的是count 值 import React, {Fragment, useState, useEffect, useRef, useCallback} from "react";
const useInterval = (callback: any, val: any) => {
const saveCallback = useRef();
useEffect(() => {
saveCallback.current = val
},[val]);
useEffect(() => {
let id = setInterval(() => callback(saveCallback.current), 1000);
return () => clearInterval(id);
}, []);
};
function App() {
const [count, setCount] = useState(0);
useInterval((val: number) => {
setCount(val + 1);
}, count);
return (
<Fragment>
<p> count: {count} </p>
</Fragment>
);
}
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
定时器没有获取到最新的state
定时器中的count 会一直会0,
因为定时器一直引用着旧的变量。
demo
解决方法:
用一个变量来保存引用值,在每次react执行时更新。既然使用hook,我们可以用useRef来保存这个引用
demo
或者在外层作用域保存这个变量(注意这里会出现多个组件引用同一个变量的问题:参考3楼的demo)
我们可以把这个功能包装成hooks,demo
参考 facebook/react#14543
The text was updated successfully, but these errors were encountered: