Next.js与TypeScript从零起步学习笔记-3.参数传
2020-01-14 本文已影响0人
KunHo
接上节内容,此文章,会介绍参数传递
参考官网:https://nextjs.org/learn/basics/getting-started
开发环境:
window10 x64
node v10.16.3
npm v6.13.4
1.参数传递
1.1. query strings传递
这个没什么特别,就是把参数放到url,然后另一个页面通过url接收罢了.
我们现在在home页加一个跳转链接,点击时候跳转到about页,顺带把'from_home'这个参数值传过去.
修改'pages/index.tsx'文件,加上如下代码:
<Link href={`/about?param=from_home`}>
<a>to about page</a>
</Link>
如图1:

然后我们修改'pages/about.tsx'文件,让它接收一下参数,启动一下,就能看到效果.
//pages/about.tsx
import Header from '../components/Header';
import { useRouter } from 'next/router'; //引入路由
const About = () => {
const router = useRouter(); //初始化路由
return (
<div>
<Header pageName='about'/>
<p>This is the about page</p>
<p>This param from home page:{router.query.param}</p>{/* 接收来自home传来的参数 */}
</div>
);
}
export default About;
启动服务器,在home页点击'to about page',可以看到效果,如图2:

1.2. 路由传递
通过query strings传递,url是这个样子的:'http://localhost:3000/about?param=from_home'
有人会觉得这样不好看,参数暴露之类的,那么我们是否能约束一下,自定义一个传递格式呢?
答案是肯定的,这里介绍路由传递:
ps:官网都是用id做例子,但我觉得id太正式,难免让人联想到id是不是特殊字段,不能变?如图3,官网示例

自己测了一下,其实并不一定要命名为'id',你改其他名字也行.
首先,我们需要在'pages'文件夹下建一个新文件夹加'p',然后'p'文件夹下创建一个文件'[param].tsx',这个文件名"[param]"表示路由参数的名字,然后我们在[param].tsx敲入如下代码:
//pages/p/[param].tsx
import { useRouter } from 'next/router'; //引入路由
const DynamicRouting = () => {
const router = useRouter(); //初始化路由
return (
<div>
<p>This is Dynamic Routing Page</p>
<p>This param from home page by route:{router.query.param}</p>{/* 接收来自home传来的参数 */}
</div>
);
}
export default DynamicRouting;
如图4:

现在,我们在home页面,写一个链接跳转过去路由传递页面([param].tsx)
在'page/index.tsx'添加如下代码
//pages/index.tsx
<br/><br/>
<Link href="/p/[param]" as={`/p/from_home`}>
<a>to about page by route </a>
</Link>
如图5:

注意蓝色图5的蓝色框,那是参数,在'pages/p/[param].tsx'中,会通过'router.query.param'拿到.保存一下,可以在浏览器看到效果,如图6:
