静待秋风
吹拂眉梢
---------写下便是永恒
2022 年 5 月 5 日,一个新的hook提案:useEvent。
其目的是返回一个永远引用不变(always-stable)的事件处理函数
const [text, setText] = useState("");const onClick = () => {sendMessage(text);};return <SendButton onClick={onClick} />;
}
为了访问最新的 state,onClick在每次chat组件更新时,都会声明一个新的函数(引用变化)
React 比较两个组件要diff 前,会对props 进行浅比较
同时它还会破坏你的 memo 优化
const SendButton = (() => {});
优化:
function Chat() {const [text, setText] = useState("");const onClick = useCallback(() => {sendMessage(text);}, [text]);return <SendButton onClick={onClick} />;
}
当text变化时,引用还是会改变,依然会带来子组件没必要的更新。。。
function Chat() {const [text, setText] = useState("");const onClick = useEvent(() => {sendMessage(text);});return <SendButton onClick={onClick} />;
}
onClick已经一直是引用不变的了,而且可以访问到最新的 text。
function useEvent(handler) {const handlerRef = useRef(null);// In a real implementation, this would run before layout effectsuseLayoutEffect(() => {handlerRef.current = handler;});return useCallback((...args) => {// In a real implementation, this would throw if called during renderconst fn = handlerRef.current;return fn(...args);}, []);
}
最核心的地方就是使用 useRef 维持最新引用以及缓存住外层的 function
不可避免的需要改动 fiber tree commit 阶段逻辑
本文发布于:2024-01-30 20:51:29,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170661911922751.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |