首页 > 解决方案 > 在 Storybook 的 preview.ts 中使用 addDecorator 会抛出比之前渲染更多的钩子

问题描述

阅读来自 Chromatic 的资源加载文档,解决方案 B:检查字体是否已加载到装饰器部分。

主要是想在渲染故事之前加载我们的字体。该解决方案建议使用addDecoratorwhere 简单的FC我们可以预加载字体,一旦加载它们就可以使用story().

请参阅建议的装饰器preview.ts

import isChromatic from "chromatic/isChromatic";

if (isChromatic() && document.fonts) {
  addDecorator((story) => {
    const [isLoadingFonts, setIsLoadingFonts] = useState(true);

    useEffect(() => {
      Promise.all([document.fonts.load("1em Roboto")]).then(() =>
        setIsLoadingFonts(false)
      );
    }, []);

    return isLoadingFonts ? null : story();
  });
}

出于某种原因,这会在违反Hooks 规则时引发通常的错误:

渲染的钩子比上一次渲染时更多

截屏

到目前为止我已经尝试过:

主要是我试图删除useEffect呈现故事的内容:

if (isChromatic() && document.fonts) {
  addDecorator((story) => {
    const [isLoadingFonts, setIsLoadingFonts] = useState(true);
   
    return story();
  });
}

错误也消失了,但字体导致我们的屏幕截图测试和以前一样导致不一致的变化。

问题:

. _ FC_addDecorator

有什么可以使这个错误消失的吗?我愿意接受任何建议。也许我在这里错过了一些东西,谢谢!

标签: reactjsstorybookchromatic

解决方案


主要解决我们这一问题的方法是从main.ts一个被addons调用的@storybook/addon-knobs.

也从preview.tsto重命名preview.tsx并使用装饰器有点不同,如下所示:

export const decorators = [
  Story => {
    const [isLoadingFonts, setIsLoadingFonts] = useState(true)

    useEffect(() => {
      const call = async () => {
        await document.fonts.load('1em Roboto')

        setIsLoadingFonts(false)
      }

      call()
    }, [])

    return isLoadingFonts ? <>Fonts are loading...</> : <Story />
  },
]

我们像上面一样使用addDecorator和用作导出const decorators


推荐阅读