-
Notifications
You must be signed in to change notification settings - Fork 3.2k
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
精读《React useEvent RFC》 #415
Comments
|
这就是 hooks 带来的副作用,一直在打补丁。 |
参考一下 vue useRef 的设计,也许可以这样?引入太多机制不太好吧 export function useRef<T>(value: T) {
const ref = React.useRef(value);
const [$1, renderSetter] = React.useState(value);
const setState = React.useCallback((newValue: T) => {
ref.current = value;
renderSetter(newValue);
}, []);
return [ref, setState] as const;
}
export function App() {
const [countRef, setCount] = useRef(0);
const onXXXCallback = React.useCallback(() => {
countRef.current; // 始终是最新的 state, onXXXCallback 也是稳定的
}, []);
return (
<div onClick={() => setCount(countRef.current + 1)}>
{ countRef.current }
</div>
);
} 也许有个更快的方式, useState 再多返回一个 getter const [count, setCount, getCount] = React.useState(0); |
@eczn 不错的想法。有个小问题,这样对于 props 传入的值都要包裹一层 useRef,用起来还是不如 useEvent 方便。 |
我觉得这里的意思应该是说,useEvent示例里面的useLayoutEffect的执行时机,应该在其他的layout effects之前 |
// (!) Approximate behavior
function useEvent(handler) {
const handlerRef = useRef(null);
// 新手求问,这里为啥要包裹一层,不能直接赋值吗
useLayoutEffect(() => {
handlerRef.current = handler;
});
return useCallback((...args) => {
// In a real implementation, this would throw if called during render
const fn = handlerRef.current;
return fn(...args);
}, []);
} |
收到
|
@GitHdu 应该是为了模仿原生 useEvent 的行为 |
@AndyBoat 抛开模仿原生 useEvent 的行为不说, |
“值并不是真正意义上的实时”这个论点其实从react设计上看它是做不到实时的,就算我们不用useCallback、useEvent这些hook,定义成纯函数也是做不到的(除了ref),因为都存在闭包问题,只有在组件再次渲染之后才回去更新值 |
useEvent 这个提案解决了 useCallback 的痛,本周我们结合 RFC 原文与解读文章 What the useEvent React hook is (and isn't) 一起了解下这个提案。
精读《React useEvent RFC》
The text was updated successfully, but these errors were encountered: