javascript - React Context 更改导致应用程序冻结
问题描述
我有一个 React Context 存储图像链接以及我们是否悬停在链接上。它的工作原理是这样的:当一个人悬停在一个链接上时,我们设置上下文来表示我们正在悬停在一个链接上,我们给它一个图像 url,然后上下文用图像更新一个组件。
问题是当您将鼠标悬停在链接上时,应用程序会完全冻结 1 秒钟,然后才显示图像。它在 FireFox 上运行良好,但在 Safari 或 Chrome 上无法运行。
上下文组件
export const CursorContext = React.createContext();
export const CursorProvider = ({ children }) => {
const [image, rawSetImage] = React.useState(null);
const contextValue = React.useMemo(() => {
function setImage(newValue) {
rawSetImage(newValue);
}
return {
image,
setImage,
};
}, [image, rawSetImage]);
return <CursorContext.Provider value={contextValue}>{children}</CursorContext.Provider>;
};
链接悬停组件
const PhotoLink = ({ data }) => {
const { setImage } = useContext(CursorContext);
const [hovering, setHovering] = useState(false);
useMemo(() => {
if (hovering)
setImage({
hovering: true,
url: data.headshot.url,
});
else
setImage({
hovering: false,
url: data.headshot.url,
});
}, [hovering]);
return (
<a onMouseEnter={() => setHovering(true)} onMouseLeave={() => setHovering(false)}>
Hover me to see photo
</a>
);
};
图像组件
const CursorImage = () => {
const { image } = React.useContext(CursorContext);
if (!image) return null;
return (
<StyledImage
src={image.url}
alt={image.alt}
style={{ opacity: image.hovering ? 1 : 0 }}
/>
);
};
解决方案
我在这里阅读了防止重新渲染的内容: https ://github.com/facebook/react/issues/15156
遵循第三个选项示例
function Button() {
let appContextValue = useContext(AppContext);
let theme = appContextValue.theme; // Your "selector"
return useMemo(() => {
// The rest of your rendering logic
return <ExpensiveTree className={theme} />;
}, [theme])
}
您可以尝试以下方法吗?
链接悬停组件
const PhotoLink = ({ data }) => {
const {setImage} = useContext(CursorContext)
let image = setImage.data
推荐阅读
- python - Selenium for Python:如何在 Send_Keys() 之后启动文件上传
- c# - 从桌面抓取文件并添加到我的网站,就像在 Google Drive 中一样
- c++ - 在某些枚举模板案例中启用类构造函数
- elasticsearch - ElasticSearch 过滤具有多个术语的别名
- c - 改进 .dat 文件的解码
- scala - Spark Dataframe - 计算列之间的对(Scala)
- python - 用python检查它是否是一个魔方
- assembly - 如何打印 IA32 汇编代码的变量值?
- sqlite - 如何更新sqlite日期时间格式
- javascript - 按字段的部分值对 Kendo Grid 中的字段进行分组