简体   繁体   English

通过 Link 传递 id 到 getServerSideProps :next js

[英]passing id through Link to getServerSideProps :next js

i have some alert compoents.我有一些警报组件。 from each of the compoent i want to pass the itm._id从我想传递的每个组件中传递 itm._id

and recive it in [itm].jsx in the same folder in the [itm].jsx i want to use it in the getServerSideProps funtion to fetch data并在 [itm].jsx 的同一文件夹中的 [itm].jsx 中接收它我想在 getServerSideProps 函数中使用它来获取数据

index.jsx索引.jsx

  <div className="question11">
            {data.map((itm) => (
              <Link
                key={itm._id}
                href={{
                  pathname: "/[itm]",
                  query: itm._id,
                }}
                as={`/${encodeURIComponent(
                  itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
                    / /g,
                    "-"
                  )
                )}`}
              >
                <Alert className="question13">{itm.Name}</Alert>
              </Link>
            ))}
          </div>

flowing is the getServerSideProps function the error now i am getting is that流动的是 getServerSideProps 函数我现在得到的错误是

Server Error FetchError: invalid json response body at https://askover.wixten.com/questone/[object%20Object] reason: Unexpected token < in JSON at position 0

i think the error is id is recived as object how do i fix this我认为错误是 id 被接收为对象我该如何解决这个问题

[itm].jsx [itm].jsx

export async function getServerSideProps(query) {
  var id1 = query;

  console.log(id1);
  const queryRequest = fetch("https://askover.wixten.com/questone/" + id1).then(
    async (res) => await res.json()
  );
  const answerRequest = fetch(
    "https://askover.wixten.com/answersapi/" + id1
  ).then(async (res) => await res.json());

  const responses = await Promise.all([queryRequest, answerRequest]);
  const [posts, answerPosts] = await Promise.all(responses);

  return {
    props: {
      posts,
      answerPosts,
    },
  };
}

在此处输入图像描述

在此处输入图像描述

在此处输入图像描述

Try this: In Link Tag pass query as试试这个:在链接标签通过查询作为

<div className="question11">
            {data.map((itm) => (
              <Link
                key={itm._id}
                href={{
                  pathname: "/[itm]",
                  query: {id: itm._id},
                }}
                as={`/${encodeURIComponent(
                  itm.Name.replace(/[^a-zA-Z0-9 - _ . ~]/g, "").replace(
                    / /g,
                    "-"
                  )
                )}`}
              >
                <Alert className="question13">{itm.Name}</Alert>
              </Link>
            ))}
          </div>

And in getserversideprops you can access it like this在 getserversideprops 你可以像这样访问它

export async function getServerSideProps(context) {
  console.log(contex.params.id)  //If doesn't work use context.query.id
}

You have to receive itm from query like below.您必须从如下查询中接收 query itself a object.查询自己一个对象。 Inside object your path variable exists as your dynamic filename.在对象内部,您的路径变量作为您的动态文件名存在。 You are fetching data by object.您正在按对象获取数据。 you have to fetch data by itm alias as id1 .您必须通过它的别名获取数据 id1

export async function getServerSideProps({ query }) {
  var {itm: id1} = query;
  ...

  return {
    props: {
      posts,
      answerPosts,
    },
  };
}

If you see the documentation for getServerSideProps you'll see the parameter is called context - this is an object, not the id you're expecting.如果您查看getServerSideProps的文档,您会看到参数称为context - 这是一个对象,而不是您期望的 id。

https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props

export async function getServerSideProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

Quote:引用:

The context parameter is an object containing the following keys: context 参数是一个包含以下键的对象:

  • req: The HTTP IncomingMessage object. req:HTTP IncomingMessage 对象。
  • res: The HTTP response object. res:HTTP 响应对象。
  • query: An object representing the query string.查询:表示查询字符串的对象。

(others removed) (其他已删除)

Therefore your query params will be in context.query .因此,您的查询参数将位于context.query中。

Try this:尝试这个:

export async function getServerSideProps(context) {
  const query = context.query
  console.log(query?.itm);
  // ^  
}

You named the query param itm (as the file is called [itm].tsx) - so context.query.itm should give you the value you need.您将查询参数命名为itm (因为文件称为 [itm].tsx) - 因此 context.query.itm 应该为您提供所需的值。 Check in the console before you add the URL.在添加 URL 之前检查控制台。

I think the issue is that you're not destructuring the query from the parameters of getServerSideProps The error tells you you are making a request to /[object object] which means your id is not a string it's the entire props object of the getServerSideProps function.我认为问题在于您没有从 getServerSideProps 的参数中解构查询错误告诉您您正在向 /[object object] 发出请求,这意味着您的 id 不是字符串它是 getServerSideProps 函数的整个 props 对象.

export async function getServerSideProps(query)导出异步函数 getServerSideProps(query)

replace it with将其替换为

export async function getServerSideProps({query})导出异步函数 getServerSideProps({query})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM