reactjs - 在 Storybook 的 preview.ts 中使用 addDecorator 会抛出比之前渲染更多的钩子
问题描述
阅读来自 Chromatic 的资源加载文档,解决方案 B:检查字体是否已加载到装饰器部分。
主要是想在渲染故事之前加载我们的字体。该解决方案建议使用addDecorator
where 简单的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
有什么可以使这个错误消失的吗?我愿意接受任何建议。也许我在这里错过了一些东西,谢谢!
解决方案
主要解决我们这一问题的方法是从main.ts
一个被addons
调用的@storybook/addon-knobs
.
也从preview.ts
to重命名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
。
推荐阅读
- python - 以 CSV 格式导出数据,但设置了不同的列。可以通过图书馆完成吗?
- java - 如何在 Spring MVC 中设计 API?
- python - 如何从带有字符串的列表中创建子列表?
- php - 警告:尝试访问 C 中 null 类型值的数组偏移量:
- python - 尝试使用 webbrowser 库搜索特殊字符不起作用
- linux - 如何发现 (RT)NETLINK 套接字连接到的网络命名空间?
- reactjs - 在 API 内的嵌套对象中达到价值
- flutter - Dart - 子类是否隐式继承 const 构造函数?
- c - “void *”类型的值不能分配给“link”的空类型。'=': 无法从 'void *' 转换为 'link'
- java - Unchecked Cast 警告 - 显示类型参数但不显示具体类型?