首页 > 解决方案 > 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 }}
    />
  );
};

标签: javascriptreactjs

解决方案


我在这里阅读了防止重新渲染的内容: 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


推荐阅读