我在使用 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/