javascript - 如何在 Next JS 中使用对象数组进行路由?

标签 javascript reactjs next.js

我一直在努力使用 next js 路由查询方法来路由页面。我正在传递对象的原始数组,但它在页面中变空了。我一直在研究,我找到了一个解决方案来使用 JSON.stringify(result) 并在另一个页面中使用 JSON.parse(query.result) 解析它,这个工作了。但是当我在页面重新加载时使用这种方法时,页面崩溃并且浏览器显示以下错误。

This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 431

我在 index.js 中的代码是

<Link href={{
  pathname: "/TvShows",
  query: {
    result: JSON.stringify(result),
    //result: [result],
    img: img,
    index: index,
  }}}
  //as={"/TvShows"}
>

目标页面是Tvshows.js

首先我定义了一个常量

const [result, setResult] = useState([]);
const [index, setIndex] = useState("");
const [img, setImg] = useState("");
const router = useRouter();
const query = router.query;

然后

useEffect (()=>{
  if(router.isReady){
    //console.log(result);
    const res = JSON.parse(query.result);
    setResult(res);
    setIndex(query.index);
    setImg(query.img);
    //console.log(res);
    //router.isReady= false;
  }
},[router.isReady])

问题是当我严格地解析这些 JSON 时。为什么会这样?

并注意:在页面的 url 部分,它使用了数据,而且它非常长。(也许这会以某种方式对其产生影响)。将数组传递到页面的最佳方式是什么?

JSON.strimgify(result) 中传递的本地数据

const Shows = [
   {
     id: 1,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 2,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 3,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
   {
     id: 4,
     title: "title1",
     img: "imgURL",
     desc: "ddescription1"
   },
] export default Shows;

最佳答案

有趣的是,我不能在我的项目中使用“code”这个词作为查询参数,所以我将它重命名为 codeTerm。 首先,我建议您远离一些关键字,例如“索引”或“代码”等。

在您的 TvShows 组件中,尝试像下面这样控制查询对象

import { withRouter } from 'next/router';

const TvShows = (props) => {
  // the rest of your code
  useEffect(() => {
    console.log(props.router.query);
    if (props.router.query.result)
      console.log(JSON.parse(props.router.query.result));
  }, [props.router]);
  // the rest of your code
}

export default withRouter(TvShows);

你不需要那个

const router = useRouter();
const query = router.query;

更新

你能尝试使用 next/router 而不是 next/link 来路由用户吗?

import Router from 'next/router';

Router.push(
  {
    pathname: '/TvShows',
    query: {
      result: JSON.stringify(result),
      img: img,
      index: index,
    },
  }
);

这应该给你你想要的,这是结果

Parsed

关于javascript - 如何在 Next JS 中使用对象数组进行路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73324279/

相关文章:

javascript - 如何在 Next.js 中获取仅限 http 的 cookie 值?

javascript - 如何在开 Jest 中使用模拟更改来测试 FileReader onload?

promise - 如何使用 SWR nextjs hook 在一个页面中进行多个调用?

javascript - jQuery 选择除一个 ID 之外的所有类

javascript - chrome.extension.sendRequest() 内存泄漏

reactjs - React i18next Backend-Path 在本地和生产环境中不同

reactjs - 刷新页面时Cloudfront返回403禁止

javascript - 如何使用 NextJS 使用自托管字体?

javascript - 使用google api从位置中提取省份

javascript - 根据模式将字符串分成 block