【问题标题】:useRouter not working inside getInitialPropsuseRouter 在 getInitialProps 中不起作用
【发布时间】:2020-02-12 20:48:05
【问题描述】:

我正在尝试使用 POST 方法从 API 获取数据,但是,我正在努力将数据设置为 post

import { useRouter } from 'next/router';
import Layout from '../../components/MyLayout';
import Settings from '../../components/Settings';

const Post = props =>{
    //works if I use here
    const router = useRouter();
  return (
    <Layout>
      <h1>{router.query.id}</h1>
      <p>This is the blog post content.</p>
    </Layout>
  );
}

export default Post;

Post.getInitialProps = async function(){
    //trying to get data ($_GET)
    const router = useRouter();
    const data = router.query;
    //
    const FormData = new URLSearchParams();
    const res = await fetch(Settings.api+'viewPost',{
        method: 'POST',
        headers:{
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: FormData,
    });
    const obj = await res.json();
    return(
        obj
    );
}

我收到以下错误

无效的挂钩调用。 Hooks 只能在 a 的主体内部调用 功能组件。这可能发生在以下情况之一 原因: 1. React 和渲染器的版本可能不匹配(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能在同一个应用程序中拥有多个 React 副本请参阅 *** 了解有关如何调试和 解决这个问题。

我刚刚了解到这一点,抱歉这个愚蠢的问题。我真的很感激任何答案。谢谢。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    我和你做了完全相同的事情(尝试在getinitialProps中使用useRouter)并得到同样的错误,然后我四处搜索并找到how to get query string parameter in next,所以要回答你的问题,你不需要useRouter in在这种情况下,而是使用 getInitialProps (props) 并找到查询参数来获取您的数据或 Id 或其他任何内容。希望对您有所帮助。

    Post.getInitialProps = async function({ query }){
       const { data } = query;
         ...................
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 2021-06-19
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多