【问题标题】:useRouter(); inside getServerSideProps :next js用户路由器();在 getServerSideProps 里面:下一个 js
【发布时间】:2022-02-09 20:29:35
【问题描述】:

我正在尝试在我的代码中使用 getgetServerSideProps,但我无法做到,因为我无法通过 router.query.itmid;

export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  const router = useRouter();
  var id = router.query.itmid;
  // You can use any data fetching library

  const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
  console.log("check");
  console.log("dada");
  const posts = await res.json();

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  };
}

这是我尝试过的 https://codesandbox.io/s/youthful-lucy-427g1?file=/src/App.js

我是下一个 js 的新手,而且我对下一个 js 了解不多,所以如果我理解我会问这个问题的文档,请不要告诉我阅读文档

【问题讨论】:

    标签: javascript reactjs next.js


    【解决方案1】:

    您应该在 getServerSideProps 中使用上下文来获取查询参数

    export async function getServerSideProps(ctx) {
      // Call an external API endpoint to get posts
      var id = ctx.query.itmid;
      // You can use any data fetching library
    
      const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
      console.log("check");
      console.log("dada");
      const posts = await res.json();
    
      // By returning { props: { posts } }, the Blog component
      // will receive `posts` as a prop at build time
      return {
        props: {
          posts,
        },
      };
    }
    

    【讨论】:

      【解决方案2】:

      useRouter用于客户端路由,可以在客户端使用,getServerSideProps会在服务端执行。

      由于这个原因,您不能在 getServerSideProps 中使用 useRouter()。

      如果您想访问 getServerSideProps 中的查询参数,那么您可以使用 context.query.[parameter],这样您的代码将如下所示

      export async function getServerSideProps(ctx) {
        // Call an external API endpoint to get posts
        var id = ctx.query.itmid;
        // You can use any data fetching library
      
        const res = await fetch("https://ask-over.herokuapp.com/questone/" + id);
        console.log("check");
        console.log("dada");
        const posts = await res.json();
      
        // By returning { props: { posts } }, the Blog component
        // will receive `posts` as a prop at build time
        return {
          props: {
            posts,
          },
        };
      }
      

      【讨论】:

        猜你喜欢
        • 2022-10-12
        • 2020-12-10
        • 2023-01-19
        • 2021-08-04
        • 1970-01-01
        • 2021-10-17
        • 2020-12-19
        • 1970-01-01
        • 2023-02-23
        相关资源
        最近更新 更多