在Next JS - App Route - Typescript中将数据从一页发送到另一页

fumotvh3  于 2023-08-04  发布在  TypeScript
关注(0)|答案(2)|浏览(137)

请帮助,我需要从一个页面的数组中获取数据,然后将其显示在另一个页面上。我正在使用NextJs,使用Typescript,AppRoute这是我的代码:
app/page.tsx:

import Image from 'next/image'
import Link from 'next/link'

const listMember = [
  {
    id: 1,
    name: "name1",
    age: 20,
  },
    {
    id: 2,
    name: "name2",
    age: 18,
  },
    {
    id: 3,
    name: "name3",
    age: 2,
  }
]

export default function HomePage() {
  return (
    <>
      <ul className="px-5">
        {listMember.map(member =>
          <li>
            <Link
              href={{
                pathname: "/Detail",
                query: member.name
              }}>{member.name}</Link>
          </li>
        )}
      </ul>
    </>
  )
}

字符串
app/Detail/page.tsx

import HomePage from "../page";

export default function Detail() {
    return (
        <>
            <h1> 
                This is detail page of {HomePage.listMember.name}
            </h1>
        </>
    )
}


我尝试过使用路由,但不工作

4bbkushb

4bbkushb1#

您需要从您的主页导出列表

export const listMember = [
  {
    id: 1,
    name: "name1",
    age: 20,
  },
    {
    id: 2,
    name: "name2",
    age: 18,
  },
    {
    id: 3,
    name: "name3",
    age: 2,
  }
]

字符串
然后从详细页面访问查询参数并找到参数,如下所示:

import { useSearchParams } from 'next/navigation'
import HomePage,{listMember} from "../page";

export default function Detail() {
const searchParams = useSearchParams()
const name = searchParams.get('name')

  const member = listMember.find(member => member.name === name);

    return (
        <>
            <h1> 
                This is detail page of {member?.name}
            </h1>
        </>
    )
}

cngwdvgl

cngwdvgl2#

更改为

export const listMember = [...
...

个字符

相关问题