【问题标题】:NextJS useRouter error when used inside function bodyNextJS useRouter 在函数体内使用时出错
【发布时间】:2021-05-29 03:54:01
【问题描述】:

我希望这是一个简单的问题。我想不通为什么它会这样做。无论如何,使用 NextJS,我正在尝试使用 useRouter 挂钩访问路由器中的参数,并将其与 querystring 插件组合以拆分 asPath,因为如果使用无状态,NextJS 不允许您访问路由器的查询部分。这是我的代码:

import { useRouter } from 'next/router';
import queryString from "query-string";

const withPageRouter = (router) => {
    router.query = { ...queryString.parse(router.asPath.split(/\?/)[1]) };
    return router;
  };

function getRouterParams(){
  const router = useRouter();
  router = withPageRouter(router);
  return router;
}

export async function getTown() {
const town = await getRouterParams();
return town;
}

现在当我尝试运行它时,我得到了这个错误:

Server Error

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source

lib/api.js (34:26) @ getRouterParams

  32 | 
  33 | function getRouterParams(){
> 34 |   const router = useRouter();
     |                          ^
  35 |   router = withPageRouter(router);
  36 |   return router;
  37 | }

但在我看来应该没问题;它在函数体中吗?我觉得我错过了一些明显的东西。感谢您的帮助。

【问题讨论】:

  • @Man of Action 是正确的。您需要将路由器直接导入为import router from "next/router"

标签: javascript reactjs next.js next-router


【解决方案1】:

你不能在普通函数中调用useRouter()。

你只能在 React 函数组件的 Top 内调用 useRouter() 或自定义钩子

在此处了解有关 Hooks 规则的更多信息:https://reactjs.org/docs/hooks-rules.html

【讨论】:

    【解决方案2】:

    作为useRouter 的替代品,您可能想要使用withRouter(可用于类组件)。另请参阅以下相关的 SO 问题:

    How to use "useRouter()" from next.js in a class component?

    import { withRouter } from 'next/router'
    import React from "react";
    
    export default withRouter(class extends React.Component {
      render() {
        return (
          <div>{ this.props.router.query.id }</div>
        )
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2022-08-03
      • 2020-09-20
      • 2021-06-19
      • 2023-03-03
      • 2023-02-18
      • 2023-03-26
      • 2016-03-15
      • 2018-04-17
      • 1970-01-01
      相关资源
      最近更新 更多