【问题标题】:next/router: Cannot read property 'pathname' of null (storybook)下一个/路由器:无法读取 null 的属性“路径名”(故事书)
【发布时间】:2020-10-09 10:40:54
【问题描述】:

我有一个使用 Next.js 和 MaterialUI 的应用程序。为了让 Link 组件与 MaterialUI 一起正常工作,我有一个特殊的 Link 组件,如下所示:

function Link(props) {
  const {
    href,
    activeClassName = 'active',
    className: classNameProps,
    innerRef,
    naked,
    prefetch,
    ...other
  } = props;

  const router = useRouter();
  const pathname = typeof href === 'string' ? href : href.pathname;
  const className = clsx(classNameProps, {
    [activeClassName]: router.pathname === pathname && activeClassName
  });

  if (naked) {
    return (
      <NextComposed
        className={className}
        ref={innerRef}
        href={href}
        prefetch={prefetch}
        {...other}
      />
    );
  }

  return (
    <MuiLink component={NextComposed} className={className} ref={innerRef} href={href} {...other} />
  );
}

当我需要它时,它绝对可以正常工作。但是,当我开始将组件(使用此链接)添加到 Storybook 时,出现错误:

Uncaught TypeError: Cannot read property 'pathname' of null
        at Link 

我添加到 Storybook 的组件中的链接使用示例:

const MyComponent = (props) => (<Button
                    className={classes.loginButton}
                    disableRipple
                    edge="end"
                    variant="contained"
                    color="secondary"
                    component={Link}
                    naked
                    href="/login"
                  >
                    Login
                  </Button>)

当我尝试使用 console.log() 路由器时,我确实得到了 null,这很奇怪。 我在这里做错了什么?

【问题讨论】:

    标签: material-ui next.js storybook next-router


    【解决方案1】:

    我在升级到 Next v9.5 时遇到了同样的问题。看起来Link 组件假定下一个路由器将存在。

    This PR 似乎解决了这个问题。升级到v9.5.1-canary.1 version 为我解决了这个问题。

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 2021-09-06
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 2015-05-25
      • 2019-08-28
      • 2022-11-20
      • 2021-12-19
      相关资源
      最近更新 更多