如何为具有 redux 连接组件作为孙子组件的组件编写故事书故事? [英] How do I write a storybook story for a component that has redux-connected component as grandchild?

查看:67
本文介绍了如何为具有 redux 连接组件作为孙子组件的组件编写故事书故事?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在根据现有代码库构建 Storybook UI 库.编写代码时并没有考虑到组件驱动开发.在很多情况下,组件呈现连接到 Redux 存储的后代.

We are building a Storybook UI library from our existing code base. The code wasn't written with component driven development in mind. There are many instances where a component renders descendants that are connected to the Redux store.

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

E.g., Parent (connected) -> Child (unconnected) -> Grandchild (connected)

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

Now if I'm building a story for Parent, I understand how to pass hard-coded data as a prop to an immediate child component in order to avoid Redux all together. However, I can't figure out how to do this when the connected component is more deeply nested.

理想情况下,我根本不想在故事中使用 Redux,但即使我确实初始化了一个 Redux 存储并将父组件包装在一个 Provider 中,如上所述 这里,这甚至可以连接孙组件吗?

Ideally I don't want to have to use Redux at all for stories, but even if I do initialize a Redux store and wrap the parent component in a Provider as described here, would this even work to connect the grandchild component?

任何想法都会有所帮助.

Any ideas would be helpful.

推荐答案

当使用 storybook 时,你可以添加一个 装饰器 适用于所有故事(请参阅最新 API 的链接).

When using storybook you can add a Decorator for all stories (see link for most updated API).

通常使用状态管理器存储提供程序包装您的故事,以免破坏故事,避免为每个故事添加一个 store".>

It is common to wrap your stories with the state manager store provider in order to not break the story avoiding "adding a store for each story".

// @ 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);

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

Note that you can avoid connecting all your components with redux-hooks which in addition removes all the boilerplate code of redux.

React Redux 现在提供一组钩子 API 作为现有 connect() 高阶组件的替代方案.这些 API 允许您订阅 Redux 存储和分派操作,而无需将组件包装在 connect() 中.

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().

这篇关于如何为具有 redux 连接组件作为孙子组件的组件编写故事书故事?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆