reactjs - 我在使用 NextJs useRouter 时遇到了问题

标签 reactjs next.js

我在使用 NextJs useRouter 时遇到问题。

我有一个在路径之间导航的函数,我使用 useRouter 来做到这一点,我在一个包含数组对象的库中写道:

router = useRouter()

const actions = [
  {
  ...
    perform: (e) => router.push('/'),
  ...
  }
]

但它会导致错误 TypeError: Cannot read properties of null (reading 'useContext')

  2 | import {useRouter} from 'next/router'
  3 | 
> 4 | const { router } = useRouter()
    |                            ^
  5 | 
  6 | const actions = [
  7 |   {

我将这个库导入到另一个组件,这就是 _app.js 的样子:

...
<div className={'webkit selection'+theme}>
   <CmdBar theme={theme}/>  => this is where the library imported in
   <Metatags description='null'/>
   <StyleReset/>
   <Component themeUse={themeUse.styles} theme={theme} {...pageProps} />
   <Bar theme={theme} setTheme={setTheme} setThemeUse={setThemeUse} themeProvider={themeProvider}/>
</div>
...

我之前在 React 和 React Router 中使用 useLocation 时遇到过这个错误,因为组件在 Route 之外。我认为这是造成这些的主要原因。

已编辑:如果我使用任何可以刷新页面的东西,它不会保持相同的 UI,所以这就是我想弄清楚的。

谢谢!

最佳答案

您好,问题的发生是因为您在顶层使用了 react Hook 。 相反,您应该在 React Functional 组件中使用钩子(Hook)。

像这样:

import { useRouter } from 'next/router'

function ActiveLink({ href }) {
  const router = useRouter()

  return (
    <a href={href}>
      This will redirect
    </a>
  )
}

export default ActiveLink

我建议你通过,Rules of Hooks

关于reactjs - 我在使用 NextJs useRouter 时遇到了问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72067405/

相关文章:

javascript - 刷新值 react 而不是操作后的值

reactjs - ACE 编辑器的薄包装,用于制作 React 组件

css - 等待 CSS 在 nextjs 静态站点上加载?

javascript - 使用 NextJS 将 SASS 变量导入 Material UI 主题

next.js - 在 Next.js 中使用 Langchain 文档加载器时如何修复 'fs module not found' 错误?

http-headers - 如何将 HTTP 安全 header 添加到 Next.js 应用程序

javascript - ReactJS - 无法读取未定义的属性 'items'

reactjs - 在react-apollo的查询组件中设置状态

reactjs - 如何解决Reactjs中的 "Firebase: Error (auth/invalid-api-key)"错误?

javascript - 在 NextJS 路由中的 slug 前面添加符号(例如@)