在 Storybook 的 preview.ts 中使用 addDecorator 会抛出比之前渲染更多的钩子

时间:2021-05-14 12:00:24

标签: reactjs storybook chromatic

阅读 Chromatic 中的资源加载文档,Solution B: Check fonts have loaded in a decorator 部分。

主要是想在渲染故事之前加载我们的字体。解决方案建议使用 addDecorator,其中使用简单的 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();
  });
}

出于某种原因,这会在违反 Rules of Hooks 时引发常见错误:

<块引用>

比上一次渲染更多的钩子

screenshot

到目前为止我尝试过的:

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

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

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

问题:

我真的没有看到任何会违反为 FC 添加的 addDecorator 中的 Rules of Hooks 的问题。

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

1 个答案:

答案 0 :(得分:0)

我们最终解决问题的主要方法是从 main.ts 中删除一个名为 addons@storybook/addon-knobs

也从 preview.ts 重命名为 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,如上。