本文介绍了如何在 Storybook 中使用 NextJS 的“useRouter()"钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在 Storybook 中使用 Next.js 中的 useRouter 钩子.但是,每次加载 Storybook 时,我都会收到无法读取 null 的属性路径名"".我该如何解决这个问题?

I've been attempting to use the useRouter hooks from Next.js inside Storybook. However, every time I load up Storybook, I get 'cannot read property 'pathname' of null'. How might I resolve this issue?

import { useRouter } from "next/router";

const NavStrip = () => {
  const router = useRouter();

  return (
    ...
            <Link href="/dashboard" passHref>
              <StyledLink active={router.pathname === "/dashboard"}>
                ...
              </StyledLink>
            </Link>
    ...
         )
}

NavStrip.stories.tsx

NavStrip.stories.tsx

import React from "react";
import NavStrip from "./index";

export default {
  component: NavStrip,
  title: "NavStrip",
};

export const Default = () => <NavStrip />;

推荐答案

你应该使用 Storybook Addon Next Router.正如 this answer 所述,您需要在 Next 中运行 Link 并且 Storybook 不会加载 Next,所以这个插件会为你模拟 Router.

You should use Storybook Addon Next Router. As this answer states, you need to run Link inside Next and Storybook doesn't load Next, so this addon will mock the Router for you.

在我的配置中,我需要做的就是:

In my config, all I needed to do was:

// .storybook/preview.js
import { withNextRouter } from 'storybook-addon-next-router';

export const decorators = [withNextRouter()]

那应该可以解决它.

这篇关于如何在 Storybook 中使用 NextJS 的“useRouter()"钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-21 16:20