Docs
Storybook Docs

加载器

加载器是异步函数,用于加载故事及其 decorators 的数据。故事的加载器在故事渲染之前运行,加载的数据通过其渲染上下文注入故事。

¥Loaders are asynchronous functions that load data for a story and its decorators. A story's loaders run before the story renders, and the loaded data injected into the story via its render context.

加载器可用于加载任何资源、延迟加载组件或从远程 API 获取数据。此功能旨在作为处理大型故事导入的性能优化。但是,args 是管理故事数据的推荐方式。我们正在围绕参数建立一个工具和技术生态系统,这些参数可能与加载的数据不兼容。

¥Loaders can be used to load any asset, lazy load components, or fetch data from a remote API. This feature was designed as a performance optimization to handle large story imports. However, args is the recommended way to manage story data. We're building up an ecosystem of tools and techniques around Args that might not be compatible with loaded data.

它们是一项高级功能(即应急方案),我们仅建议你在有其他方式无法满足的特定需求时使用它们。

¥They are an advanced feature (i.e., escape hatch), and we only recommend using them if you have a specific need that other means can't fulfill.

获取 API 数据

¥Fetching API data

故事是独立的组件示例,用于渲染作为故事的一部分或与故事一起定义为 args 的内部数据。

¥Stories are isolated component examples that render internal data defined as part of the story or alongside the story as args.

当你需要从外部(例如从远程 API)加载故事数据时,加载器很有用。考虑以下示例,该示例获取待办事项以显示在待办事项列表中:

¥Loaders are helpful when you need to load story data externally (e.g., from a remote API). Consider the following example that fetches a todo item to display in a todo list:

MyComponent.stories.ts|tsx
import type { Meta, StoryObj } from '@storybook/react';
 
import { TodoItem } from './TodoItem';
 
/*
 *👇 Render functions are a framework specific feature to allow you control on how the component renders.
 * See https://storybook.js.org/docs/api/csf
 * to learn how to use render functions.
 */
const meta: Meta<typeof TodoItem> = {
  component: TodoItem,
  render: (args, { loaded: { todo } }) => <TodoItem {...args} {...todo} />,
};
 
export default meta;
type Story = StoryObj<typeof TodoItem>;
 
export const Primary: Story = {
  loaders: [
    async () => ({
      todo: await (await fetch('https://jsonplaceholder.typicode.com/todos/1')).json(),
    }),
  ],
};

从远程 API 调用获得的响应被组合到故事上下文中的 loaded 字段中,这是故事函数的第二个参数。例如,在 React 中,故事的参数首先被传播,以优先于加载器提供的静态数据。使用其他框架(例如 Angular),你可以像平常一样编写故事。

¥The response obtained from the remote API call is combined into a loaded field on the story context, which is the second argument to a story function. For example, in React, the story's args were spread first to prioritize them over the static data provided by the loader. With other frameworks (e.g., Angular), you can write your stories as you'd usually do.

全局加载器

¥Global loaders

我们还可以通过 .storybook/preview.js 文件的 loaders 导出(这是你配置所有故事的文件)为所有故事设置一个加载器:

¥We can also set a loader for all stories via the loaders export of your .storybook/preview.js file (this is the file where you configure all stories):

.storybook/preview.ts
// Replace your-framework with the framework you are using (e.g., react, vue3)
import { Preview } from '@storybook/your-framework';
 
const preview: Preview = {
  loaders: [
    async () => ({
      currentUser: await (await fetch('https://jsonplaceholder.typicode.com/users/1')).json(),
    }),
  ],
};
 
export default preview;

在此示例中,我们为所有故事加载一个可用作 loaded.currentUser 的 "当前用户"。

¥In this example, we load a "current user" available as loaded.currentUser for all stories.

加载器继承

¥Loader inheritance

参数 一样,加载器可以在全局、组件级别和单个故事中定义(如我们所见)。

¥Like parameters, loaders can be defined globally, at the component level, and for a single story (as we’ve seen).

在适用于故事的所有级别上定义的所有加载器都在故事在 Storybook 画布中渲染之前运行。

¥All loaders, defined at all levels that apply to a story, run before the story renders in Storybook's canvas.

  • 所有加载器并行运行

    ¥All loaders run in parallel

  • 所有结果都是故事上下文中的 loaded 字段

    ¥All results are the loaded field in the story context

  • 如果有重叠的键,"later" 加载器优先(从最低到最高):

    ¥If there are keys that overlap, "later" loaders take precedence (from lowest to highest):

    • 全局加载器,按定义顺序排列

      ¥Global loaders, in the order they are defined

    • 组件加载器,按定义顺序

      ¥Component loaders, in the order they are defined

    • 故事加载器,按定义顺序排列

      ¥Story loaders, in the order they are defined