javascript - 将 id 通过 Link 传递给 getServerSideProps :next js

标签 javascript reactjs next.js

我有一些警报组件。从我想传递 itm._id 的每个组件中

并在 [itm].jsx 的同一文件夹中的 [itm].jsx 中接收它,我想在 getServerSideProps 函数中使用它来获取数据

index.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>

流动是 getServerSideProps 函数,我现在得到的错误是

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

我认为错误是 id is recided as object 我该如何解决这个问题

[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,
    },
  };
}

enter image description here

enter image description here

enter image description here

最佳答案

试试这个: 在 Link Tag 中传递查询为

<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>

在 getserversideprops 中你可以像这样访问它

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

关于javascript - 将 id 通过 Link 传递给 getServerSideProps :next js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72360423/

相关文章:

javascript - 使对象键成为等效子对象中的值

javascript - 使用 Bootstrap 和 jQuery 无法很好地呈现多个分页器

javascript - 从具有特定 src 属性的数组中抓取图像

reactjs - Material UI + Nextjs : Drawer

node.js - Node JS 中是否也需要每个 React 库?

javascript - 如何解决 Next.Js 中的内部服务器错误?

javascript - 在 Google map 中按类型显示自定义图像标记图标。

reactjs - 如何测试渲染的 React 组件的 HTML?

javascript - React - react.render() 上未处理的错误事件

reactjs - React useEffect 钩子(Hook)依赖于第二个效果