如何为将 redux 连接组件作为孙组件的组件编写故事书故事?

How do I write a storybook story for a component that has redux-connected component as grandchild?

我们正在从我们现有的代码库构建 Storybook UI 库。编写代码时并未考虑组件驱动开发。在许多情况下,组件会呈现连接到 Redux 存储的后代。

例如,父(已连接)-> 子(未连接)-> 孙(已连接)

现在,如果我正在为 Parent 构建一个故事,我就会了解如何将硬编码数据作为 prop 传递给直接的子组件,以避免一起使用 Redux。但是,当连接的组件嵌套更深时,我无法弄清楚如何执行此操作。

理想情况下,我根本不想为故事使用 Redux,但即使我确实初始化了 Redux 存储并将父组件包装在 Provider 中,如 here 所述,这是否可行连接孙组件?

任何想法都会有所帮助。

使用 storybook 时,您可以为所有故事添加 Decorator(请参阅 link 了解最新的 API)。

为了不破坏故事避免“为每个故事添加一个store,通常会使用状态管理器商店提供者包装您的故事。

// @ config.js
import { configure,  addDecorator } from '@storybook/react';

import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from 'reducers/root.reducer';

const store = createStore(rootReducer);

addDecorator(S => (
  <Provider store={store}>
    <S />
  </Provider>
));


configure(require.context('../src', true, /\.stories\.js$/), module);

请注意,您可以避免 connect 使用 redux-hooks 连接所有组件,这还会删除 redux 的所有样板代码。

React Redux now offers a set of hook APIs as an alternative to the existing connect() Higher Order Component. These APIs allow you to subscribe to the Redux store and dispatch actions, without having to wrap your components in connect().

如果您想在您的故事文件中解决问题(并且只获取您的商店),请像这样使用装饰器:

import React from "react";
import { Provider } from 'react-redux'
import Parent from "./Parent";

import { store } from "../../../redux/store";

export default = {
  title: "pages/Parent",
  component: Parent,
  decorators : [
    (Story) => (<Provider store={store}><Story/></Provider>)
  ]
};

旁注,如果这给您带来错误 useNavigate() may be used only in the context of a <Router> component.,那么您可能需要 <MemoryRouter><Provider store={store}><Story/></Provider></MemoryRouter> (import {MemoryRouter} from 'react-router-dom')