带有 react-router 的 Storybook - 你不应该在 <Router> 之外使用 <Link>

IT技术 javascript reactjs react-router storybook
2021-05-01 02:59:54

发布问题的解决方案我很难找到,尽管 Sensei 谷歌搜索技能

尽管我的带有 react-router 的应用程序运行没有任何问题 Storybook 抛出错误“不变失败:你不应该在外面使用”。

Error: Invariant failed: You should not use <Link> outside a <Router>
    at invariant (tiny-invariant.esm.js:11)
    at react-router-dom.js:181
    at updateContextConsumer (react-dom.development.js:19747)
    at beginWork$1 (react-dom.development.js:20079)
    at HTMLUnknownElement.callCallback (react-dom.development.js:358)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:410)
    at invokeGuardedCallback (react-dom.development.js:463)
    at beginWork$$1 (react-dom.development.js:25730)
    at performUnitOfWork (react-dom.development.js:24631)
    at workLoopSync (react-dom.development.js:24613)

奇怪,因为该应用程序有效(因此没有在外面使用)。

4个回答

这是对我有用的:

  1. preview.js在您的.storybook文件夹中创建一个文件
  2. 在您的preview.js文件中添加以下全局装饰器
    import React from "react";
    import { addDecorator } from "@storybook/react";
    import { MemoryRouter } from "react-router";
    
    addDecorator(story => <MemoryRouter initialEntries={['/']}>{story()}</MemoryRouter>);

笔记

  • 使用的故事书版本: "@storybook/react": "^5.3.13"
  • 基于该解决方案在这里
  • 更多关于全局装饰器的信息在这里

这对我有用。在装饰器属性中添加内存路由器。

import React from 'react';
import {MemoryRouter} from 'react-router-dom';
import //your component// from //component location//

export default {
title : //How you want your component to show in storybook eg: 'Components/Button'
component : //Specify the name of component that you imported eg: 'Button'
decorators : [(Story) => (<MemoryRouter><Story/></MemoryRouter>)] //Wrapping the story inside the router
};

对于 Storybook 6.1 版,storybook-router使用新的代码表示法。以下是单个组件的示例:

import React from 'react';
import StoryRouter from 'storybook-react-router';
import //your component// from //component location//

export default {
  title: '//your component//',
  component: //your component//,
  decorators: [StoryRouter()],
};

export const Name = () => <//your component// />;

进一步对网络滑雪的回答。将 StoryRouter 添加到您的.storybook/preview.js

import StoryRouter from 'storybook-react-router';

addDecorator(StoryRouter());

它现在可在全球范围内的每个故事中使用。